$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/