user2327201
user2327201

Reputation: 409

PHP regular expression if something is there or not

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

Answers (4)

Casimir et Hippolyte
Casimir et Hippolyte

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

Andrew Clark
Andrew Clark

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

Niet the Dark Absol
Niet the Dark Absol

Reputation: 324640

Use an optional subpattern: (?:version=)?

Upvotes: 1

Damien Overeem
Damien Overeem

Reputation: 4529

$find = '/jsfile\.js\?(version=)?[0-9]*</';

Something like this should do..

Upvotes: 0

Related Questions