preg_replace如何仅替换选择器中匹配的xxx($ 1)yyy模式 [英] preg_replace how to replace only matching xxx($1)yyy pattern inside the selector
问题描述
我正在尝试使用正则表达式仅擦除字符串的匹配部分.我正在使用preg_replace
函数,并尝试通过在匹配的部分两边加上括号来删除匹配的文本.示例:
I'm trying to use a regular expression to erase only the matching part of an string. I'm using the preg_replace
function and have tried to delete the matching text by putting parentheses around the matching portion. Example:
preg_replace('/text1(text2)text3/is','',$html);
这将整个字符串替换为".我只想删除text2,但保留text1和text3不变.如何匹配和替换仅匹配的字符串部分?
This replaces the entire string with '' though. I only want to erase text2, but leave text1 and text3 intact. How can I match and replace just the part of the string that matches?
推荐答案
在匹配模式中使用text1
和text3
,然后通过替换字符串将它们放回是一种替代方法.您可以像这样使用断言:
There is an alternative to using text1
and text3
in the match pattern and then putting them back in via the replacement string. You can use assertions like this:
preg_replace('/(?<=text1)(text2)(?=text3)/', "", $txt);
这样,正则表达式仅查找 presence ,而在应用替换时不考虑这两个字符串.
This way the regular expression looks just for the presence, but does not take the two strings into account when applying the replacement.
http://www.regular-expressions.info/lookaround.html 更多信息.
这篇关于preg_replace如何仅替换选择器中匹配的xxx($ 1)yyy模式的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!