'Removing CSS and js version via REGEX
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);
Solution 1:[1]
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.jsor.css\KForget 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.
Solution 2:[2]
$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
$1refers to the first captured group which is(css|js)to keep the extenstion.
Solution 3:[3]
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
Solution 4:[4]
$html = preg_replace('/.js(\?v=[0-9]{0,15})/s', '.js', $html);
That's work, i just want a little improvements of the code.
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|---|
| Solution 1 | The fourth bird |
| Solution 2 | |
| Solution 3 | |
| Solution 4 | Rachid Lam |
