PHP preg_replace - 不包含短语的正则表达式

标签 php preg-replace

$test = "<div><b><i>#uniquetag#</b></i></div> <div>Keep this</div>";

$test = preg_replace("/<div(.*)#uniquetag#(.*)<\/div>/i", "#uniquetag#", $test);

我想要的结果是

$test = "#uniquetag# <div>Keep this</div>";

但它返回

$test = "#uniquetag#";

我想我知道为什么。 (.*) 是贪婪的,它将搜索延伸到最后。但我不知道什么是正确的方法。

更新:

特别感谢 Ghostdog74。老问题解决了。遇到了新问题......

$test = "<div></div> <div><b><i>#uniquetag#</b></i></div> <div>Keep this</div>";

$test = preg_replace("/<div(.*)#uniquetag#(.*?)<\/div>/i", "#uniquetag#", $test);

预期结果是

$test = "<div></div> #uniquetag# <div>Keep this</div>";

但事实证明是

$test = "#uniquetag# <div>Keep this</div>";

我再次相信这是因为第一个 (.)。将其更改为 (.?) 也无济于事。需要想办法排除。

最佳答案

(.*)更改为(.*?)

关于PHP preg_replace - 不包含短语的正则表达式,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/2175378/

相关文章:

php - 使用 preg_replace 提取属性

php - 如何在 Wordpress 上获取菜单数据

php - 如何使用 Laravel 5.2 将图像添加到 Twitter Bootstrap

php - 如何在 php preg_replace 中去除 ${1}?

php - preg_replace() 找不到结束分隔符?

PHP:UTF8 中西里尔字符串的不区分大小写的 preg_replace

PHP Zend_Mail_Storage_Imap 限制消息

php图像上传检查上传照片的大小不起作用

javascript - 将电子邮件从多个电子邮件表单发送到多个电子邮件地址

php - preg_replace 将匹配计数传递给第二个参数