PHP preg_replace:帮我理解(?=:)

发布于 2024-08-14 18:26:27 字数 368 浏览 2 评论 0原文

另一个问题中,有以下几行:

$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 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(1

ゃ懵逼小萝莉 2024-08-21 18:26:27

这是一个正向预测。它查看特定的子表达式是否出现在该点之后。但它不会消耗比赛中的任何东西:

正向前瞻的工作原理是一样的。 q(?=u) 匹配后跟 uq,而不使 u 成为比赛。正向先行结构是一对圆括号,左括号后跟一个问号和一个等号。 —RegularExpressions.info

正如您可能注意到的,环视在替换文本时特别有用,因为您可以不需要将周围环境包含到替换文本中。例如,要将每个后面不跟有 uq 替换为 qu,您可以这样做

replace 'q([^u])' by 'qu\1'

,但这会捕获以下字符,因为它是匹配并稍后重新插入。您还可以使用lookaround:,

replace 'q(?!u)' by 'qu'

其中仅匹配和替换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:

Positive lookahead works just the same. q(?=u) matches a q that is followed by a u, without making the u part of the match. The positive lookahead construct is a pair of round brackets, with the opening bracket followed by a question mark and an equals sign. —RegularExpressions.info

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 a u with qu you can do

replace 'q([^u])' by 'qu\1'

but this captures the following character because it's part of the match and re-inserts it later again. You can also use lookaround:

replace 'q(?!u)' by 'qu'

where only the q gets matched and replaced, so including part of the match in the replacement string isn't necessary anymore.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文