如何用 preg_replace 替换完整匹配项?
how to replace the full match with preg_replace?
我有这个正则表达式:
https://regex101.com/r/Eaj73B/5
如您所见,它匹配给定字符串中的第 1 组和第 2 组。
但是当我在 php 中使用 preg_replace 时,它不会替换完整匹配的第 2 组:
preg_replace('/\[(\w+)[^\]]*]([^\[]+\[\?\/\])?/', '', $string)
如何替换完整匹配项?
更新:
在测试器 regex101.com 中,正则表达式确实运行良好。但在真正的 PHP 服务器上,它无法按预期工作。见下文:
使用此方法在 php7.2 的 2 台不同服务器上进行了测试,但这是结果:
public function TestReplace(){
$string = 'x[embed]some text or url[/embed]x';
return preg_replace('/\[(\w+)[^\]]*]([^\[]+\[\?\/\])?/', '', $string);
}
returns:
x一些文字或url[/embed]x
所以它只在真正的 php7.2 服务器上替换 [embed]。我真的不知道我在这里做错了什么...
我找到答案了! php preg_replace 似乎不支持某些正则表达式功能,所以我不得不稍微更改一下正则表达式。
这个适用于 php:
preg_replace('/\[\w+[^\]]*]([^\[]+\[[\a-zA-Z\/]+\])?/', '', $string);
感谢这个 post: PHP preg_replace non-greedy trouble.
所以我的结论也是像www.phpliveregex.com这样的现场测试员并不总是可靠的。
我有这个正则表达式:
https://regex101.com/r/Eaj73B/5
如您所见,它匹配给定字符串中的第 1 组和第 2 组。
但是当我在 php 中使用 preg_replace 时,它不会替换完整匹配的第 2 组:
preg_replace('/\[(\w+)[^\]]*]([^\[]+\[\?\/\])?/', '', $string)
如何替换完整匹配项?
更新:
在测试器 regex101.com 中,正则表达式确实运行良好。但在真正的 PHP 服务器上,它无法按预期工作。见下文:
使用此方法在 php7.2 的 2 台不同服务器上进行了测试,但这是结果:
public function TestReplace(){
$string = 'x[embed]some text or url[/embed]x';
return preg_replace('/\[(\w+)[^\]]*]([^\[]+\[\?\/\])?/', '', $string);
}
returns:
x一些文字或url[/embed]x
所以它只在真正的 php7.2 服务器上替换 [embed]。我真的不知道我在这里做错了什么...
我找到答案了! php preg_replace 似乎不支持某些正则表达式功能,所以我不得不稍微更改一下正则表达式。
这个适用于 php:
preg_replace('/\[\w+[^\]]*]([^\[]+\[[\a-zA-Z\/]+\])?/', '', $string);
感谢这个 post: PHP preg_replace non-greedy trouble.
所以我的结论也是像www.phpliveregex.com这样的现场测试员并不总是可靠的。