php preg_replace 如何只替换选择器内匹配的 xxx($1)yyy 模式

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/4898192/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-25 16:12:33  来源:igfitidea点击:

preg_replace how to replace only matching xxx($1)yyy pattern inside the selector

phpregexreplacepreg-matchregex-group

提问by PartySoft

I'm trying to use a regular expression to erase only the matching part of an string. I'm using the preg_replacefunction and have tried to delete the matching text by putting parentheses around the matching portion. Example:

我正在尝试使用正则表达式来仅删除字符串的匹配部分。我正在使用该preg_replace函数并尝试通过在匹配部分周围放置括号来删除匹配的文本。例子:

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?

不过,这会用 '' 替换整个字符串。我只想擦除 text2,但保持 text1 和 text3 不变。如何仅匹配和替换匹配的字符串部分?

回答by mario

There is an alternative to using text1and text3in the match pattern and then putting them back in via the replacement string. You can use assertionslike this:

还有就是要使用替代text1,并text3在匹配模式,然后把它们放回通过替换字符串。您可以使用这样的断言

preg_replace('/(?<=text1)(text2)(?=text3)/', "", $txt);

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.htmlfor more information.

http://www.regular-expressions.info/lookaround.html了解更多信息。

回答by Mansoor Siddiqui

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.:

使用反向引用(即括号)仅保留您想要记住的表达式部分。您可以通过使用召回替换字符串中的内容$1$2等:

preg_replace('/(text1)text2(text3)/is','',$html);

回答by aorcsik

Try this:

尝试这个:

$text = preg_replace("'(text1)text2(text3)'is", "", $text);

Hope it works!

希望它有效!

Edit:changed \\1\\2to $1$2which is the recommended way.

编辑:更改\\1\\2$1$2推荐的方式。

回答by abesto

The simplest way has been mentioned several types. Another idea is lookahead/lookback, they're overkill this time but often quite useful.

最简单的方法已经提到了几种类型。另一个想法是前瞻/回顾,这次它们有点矫枉过正,但通常非常有用。