PHP preg_replace 非贪心麻烦

发布于 2024-08-14 19:24:03 字数 527 浏览 2 评论 0 原文

我一直在使用以下网站来测试 PHP 正则表达式,因此我不必不断上传: http://www.spaweditor.com/scripts/regex/index.php

我正在使用以下正则表达式:

/(.*?)\.{3}/

在以下字符串上(不替换任何内容):

Non-important data...important data...more important data

并且 preg_replace 正在返回:

more important data

但我希望它返回:

important data...more important data

我认为?是非贪婪修饰符。这是怎么回事?

I've been using the following site to test a PHP regex so I don't have to constantly upload:
http://www.spaweditor.com/scripts/regex/index.php

I'm using the following regex:

/(.*?)\.{3}/

on the following string (replacing with nothing):

Non-important data...important data...more important data

and preg_replace is returning:

more important data

yet I expect it to return:

important data...more important data

I thought the ? is the non-greedy modifier. What's going on here?

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

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

发布评论

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

评论(2

手心的温暖 2024-08-21 19:24:03

您的非贪婪修饰符正在按预期工作。但是 preg_match 会将所有出现的(非贪婪)匹配替换为替换文本(在您的情况下是 "" )。如果您只想替换第一个,可以将 1 作为可选的第四个参数(限制)传递给 preg_replace 函数 (preg_replace 的 PHP 文档)。在您链接的网站上,可以通过在单词“Flags”和单词“limit”之间的文本输入中键入 1 来完成此操作。

Your non-greedy modifier is working as expected. But preg_match replaces all occurences of the the (non-greedy) match with the replacement text ("" in your case). If you want only the first one replaced, you could pass 1 as the optional 4th argument (limit) to preg_replace function (PHP docs for preg_replace). On the website you linked, this can be accomplished by typing 1 into the text input between the word "Flags" and the word "limit".

娇纵 2024-08-21 19:24:03

只是@Asaph 解决方案的一个实际示例。在此示例中,您不需要非贪婪,因为您可以指定计数。
仅用标记替换行中第一次出现的 @

 $line=preg_replace('/@/','zzzzxxxzzz',$line,1);

just an actual example of @Asaph solution. In this example ou don't need non-greediness because you can specify a count.
replace just the first occurrence of @ in a line with a marker

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