Reputation: 409
I am working with regular expressions, and I have this block of code:
$find = "/jsfile\.js?[0-9]*</";
$switch = 'jsfile.js?version=' . $version . '<';
$replace = preg_replace($find, $switch, $data);
My problem is that my JavaScript file now has ?version=<number>
. Now, if I run this script again, it will break.
Is there a way to say, using regular expressions, in my $find
string that ?version=
may or may not be there?
Upvotes: 0
Views: 167
Reputation: 89557
You can use this pattern instead:
$find = '~jsfile\.js\?\K(?>version=)?\d++(?=<)~';
$switch = 'version='. $version;
$replace = preg_replace($find, $switch, $data);
Upvotes: 0
Reputation: 208475
Try the following:
$find = '/jsfile\.js\?(version=)?[0-9]*</';
?
makes the preceding element optional, and parentheses create a group, so (version=)?
means "optionally match version=
". Note that I also escaped the ?
from earlier in the regular expression, since you want this to match a literal ?
and not make the s
optional.
In addition, I switched from double to single quotes to ensure the escaping works properly, if you were to use double quotes you would want to escape each backslash, for example:
$find = "/jsfile\\.js\\?(version=)?[0-9]*</";
Upvotes: 0
Reputation: 4529
$find = '/jsfile\.js\?(version=)?[0-9]*</';
Something like this should do..
Upvotes: 0