PHP preg_replace 非贪心的麻烦 [英] PHP preg_replace non-greedy trouble

查看:74
本文介绍了PHP preg_replace 非贪心的麻烦的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

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

并且 preg_replace 正在返回:

and preg_replace is returning:

more important data

但我希望它回来:

important data...more important data

我以为是?是非贪婪修饰符.这是怎么回事?

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

推荐答案

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

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".

这篇关于PHP preg_replace 非贪心的麻烦的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆