How can I remove the ?v=VersionNumber
after the filename
script.js?v=VersionNumber
CSS.css?v=VersionNumber
Expected result:
script.js
CSS.css
What I tried:
$html = file_get_contents('https://stackoverflow.com/');
$html = preg_replace('/.js(.*)/s', '', $html);
CodePudding user response:
$html = preg_replace('/\?v=[[:alnum:]]*/', '', $html)
Tests:
Only apply that to JS and CSS
$html = preg_replace('/(css|js)(\?v=[[:alnum:]]*)/', '$1', $html);
This pattern separates the matches to two groups (each pair of parentheses defines a group).
In the replacement
$1
refers to the first captured group which is(css|js)
to keep the extenstion.
CodePudding user response:
Looking at your answer that you want to match digits, if you want to remove the version number for either a js or css file:
\.(?:js|css)\K\?v=\d
The pattern matches
\.(?:js|css)
Match either.js
or.css
\K
Forget what is matched so far\?v=\d
match?v=
and 1 or more digits
See aRegex demo.
$re = '/\.(?:js|css)\K\?v=\d /';
$s = 'script.js?v=123
CSS.css?v=3456';
$result = preg_replace($re, '', $s);
echo $result;
Output
script.js
CSS.css
See a php demo.
CodePudding user response:
$html = preg_replace('/.js(\?v=[0-9]{0,15})/s', '.js', $html);
That's work, i just want a little improvements of the code.
CodePudding user response:
You could use strtok
to get the characters before a string
$fileURL = 'script.js?v=VersionNumber';
echo strtok($fileURL, '?');
// script.js
If you want to use preg_match_all
, you could do something like below:
$re = '/^([^?] )/m';
$str = 'index.js?params=something';
$str2 = 'index.jsparams=something';
preg_match_all($re, $str, $matches);
preg_match_all($re, $str2, $matches2);
var_dump($matches[0][0]); // return index.js
var_dump($matches[0][0]); // return index.jsparams=something
It will remove all characters after ?
. If ?
not found, it will return the original value