如何用preg_replace替换完全匹配?

问题描述 投票:-1回答:1

我有这个正则表达式:

https://regex101.com/r/Eaj73B/5

如您所见,它匹配给定字符串中的组1和组2。

但是当我在php中使用preg_replace时,它不会替换完整匹配的第2组:

preg_replace('/\[(\w+)[^\]]*]([^\[]+\[\\?\/\1\])?/', '', $string)

如何替换完整匹配?

更新:

在测试仪regex101.com中,正则表达式确实运行良好。但是在真正的PHP服务器上,它无法按预期工作。见下文:

在此方法下,使用php7.2在2个不同的服务器上进行了测试,但这是结果:

    public function TestReplace(){

    $string = 'x[embed]some text or url[/embed]x';

    return preg_replace('/\[(\w+)[^\]]*]([^\[]+\[\\?\/\1\])?/', '', $string);

}

返回:

xsome text or url [/ embed] x

因此,它仅替换[embed]在实际的php7.2服务器上。我真的不知道我在这里做错了什么...

php preg-replace
1个回答
0
投票

我找到了答案!似乎php preg_replace不支持某些正则表达式功能,因此我不得不对正则表达式进行一些更改。

这个适用于php:

preg_replace('/\[\w+[^\]]*]([^\[]+\[[\\a-zA-Z\/]+\])?/', '', $string);

感谢这篇文章:PHP preg_replace non-greedy trouble

所以我的结论还在于,像www.phpliveregex.com这样的实时测试程序并不总是可靠的。

© www.soinside.com 2019 - 2024. All rights reserved.