PHP preg_replace:帮我理解(?=:)
在另一个问题中,有以下几行:
$value='x-Cem-Date:Wed, 16 Dec 2009 15:42:28 GMT';
$value = preg_replace('/(^.+?)(?=:)/e', "strtolower('\\1')", $value);
// yields 'x-cem-date:Wed, 16 Dec 2009 15:42:28 GMT'
(?=:)
位表示搜索对于结肠来说,它必须这样做。但是,我不明白 ?=
的特定语法。那里究竟发生了什么?
In another question, there are the following lines:
$value='x-Cem-Date:Wed, 16 Dec 2009 15:42:28 GMT';
$value = preg_replace('/(^.+?)(?=:)/e', "strtolower('\\1')", $value);
// yields 'x-cem-date:Wed, 16 Dec 2009 15:42:28 GMT'
That (?=:)
bit indicates a search for the colon, it has to. But, I don't understand that particular syntax, with the ?=
. What exactly is going on there?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
这是一个正向预测。它查看特定的子表达式是否出现在该点之后。但它不会消耗比赛中的任何东西:
正如您可能注意到的,环视在替换文本时特别有用,因为您可以不需要将周围环境包含到替换文本中。例如,要将每个后面不跟有
u
的q
替换为qu
,您可以这样做,但这会捕获以下字符,因为它是匹配并稍后重新插入。您还可以使用lookaround:,
其中仅匹配和替换q,因此不再需要在替换字符串中包含部分匹配。
That's a positive lookahead. It looks whether the particular subexpression occurs after that point. But it doesn't consume anything in the match:
As you may notice, lookaround is especially helpful when replacing text since you don't need to include the surrounding environment into the replacement text. For example, to replace every
q
that is not followed by au
withqu
you can dobut this captures the following character because it's part of the match and re-inserts it later again. You can also use lookaround:
where only the q gets matched and replaced, so including part of the match in the replacement string isn't necessary anymore.