0

我正在使用正则表达式,并且我有这段代码:

 $find = "/jsfile\.js?[0-9]*</";
 $switch = 'jsfile.js?version=' . $version . '<';
 $replace = preg_replace($find, $switch, $data);

我的问题是我的 JavaScript 文件现在有?version=<number>. 现在,如果我再次运行此脚本,它将中断。

有没有办法说,使用正则表达式,在我的$find字符串中?version=可能存在也可能不存在?

4

4 回答 4

1

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

于 2013-05-10T19:20:11.030 回答
0
$find = '/jsfile\.js\?(version=)?[0-9]*</';

Something like this should do..

于 2013-05-10T19:19:58.083 回答
0

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]*</";
于 2013-05-10T19:20:23.233 回答
0

您可以改用此模式:

$find = '~jsfile\.js\?\K(?>version=)?\d++(?=<)~';
$switch = 'version='. $version;
$replace = preg_replace($find, $switch, $data);
于 2013-05-10T19:29:37.463 回答