Par*_*oft 30 php regex replace preg-match regex-group
我正在尝试使用正则表达式来仅擦除字符串的匹配部分.我正在使用该preg_replace
函数,并试图通过在匹配部分周围加上括号来删除匹配的文本.例:
preg_replace('/text1(text2)text3/is','',$html);
Run Code Online (Sandbox Code Playgroud)
这会用''代替整个字符串.我只想删除text2,但保留text1和text3.如何匹配和替换匹配的字符串部分?
mar*_*rio 42
有一种替代方法可以使用text1
和text3
匹配模式,然后通过替换字符串将它们放回去.你可以使用这样的断言:
preg_replace('/(?<=text1)(text2)(?=text3)/', "", $txt);
Run Code Online (Sandbox Code Playgroud)
这样,正则表达式仅查找存在,但在应用替换时不考虑两个字符串.
http://www.regular-expressions.info/lookaround.html了解更多信息.
Man*_*qui 37
使用反向引用(即括号)仅保留要记住的表达式部分.您可以通过使用召回替换字符串中的内容$1
,$2
等:
preg_replace('/(text1)text2(text3)/is','$1$2',$html);
Run Code Online (Sandbox Code Playgroud)
aor*_*sik 15
试试这个:
$text = preg_replace("'(text1)text2(text3)'is", "$1$2", $text);
Run Code Online (Sandbox Code Playgroud)
希望它有效!
编辑:更改\\1\\2
为$1$2
推荐的方式.
归档时间: |
|
查看次数: |
30219 次 |
最近记录: |