Rachid Lam
Rachid Lam

Reputation: 21

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);

Upvotes: 2

Views: 114

Answers (4)

medilies
medilies

Reputation: 2218

$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.

Test https://3v4l.org/K3OVO

Upvotes: 2

The fourth bird
The fourth bird

Reputation: 163362

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.

Upvotes: 2

zaidysf
zaidysf

Reputation: 502

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

Upvotes: -1

Rachid Lam
Rachid Lam

Reputation: 21

$html = preg_replace('/.js(\?v=[0-9]{0,15})/s', '.js', $html);

That's work, i just want a little improvements of the code.

Upvotes: -2

Related Questions