preg_replace 如何仅替换选择器内匹配的 xxx($1)yyy 模式
我正在尝试使用正则表达式来仅删除字符串的匹配部分。我正在使用 preg_replace
函数,并尝试通过在匹配部分周围加上括号来删除匹配文本。示例:
preg_replace('/text1(text2)text3/is','',$html);
但这会用 '' 替换整个字符串。我只想删除text2,但保留text1和text3完好无损。如何匹配并替换字符串中匹配的部分?
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);
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?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(4)
使用反向引用(即括号)仅保留您想要记住的表达式部分。您可以使用
$1
、$2
等调用替换字符串中的内容:Use backreferences (i.e. brackets) to keep only the parts of the expression that you want to remember. You can recall the contents in the replacement string by using
$1
,$2
, etc.:还有一种替代方法可以在匹配模式中使用
text1
和text3
,然后通过替换字符串将它们放回。您可以像这样使用断言:这样,正则表达式仅查找存在的情况,但在应用替换时不会考虑这两个字符串。
http://www.regular-expressions.info/lookaround.html 了解更多信息。
There is an alternative to using
text1
andtext3
in the match pattern and then putting them back in via the replacement string. You can use assertions like this: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 for more information.
试试这个:
希望它有效!
编辑:将
\\1\\2
更改为$1$2
这是推荐的方式。Try this:
Hope it works!
Edit: changed
\\1\\2
to$1$2
which is the recommended way.最简单的方式已经提到了几种类型。另一个想法是前瞻/回顾,这次它们有点矫枉过正,但通常非常有用。
The simplest way has been mentioned several types. Another idea is lookahead/lookback, they're overkill this time but often quite useful.