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

发布于 2024-10-16 01:04:38 字数 240 浏览 4 评论 0原文

我正在尝试使用正则表达式来仅删除字符串的匹配部分。我正在使用 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 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(4

我偏爱纯白色 2024-10-23 01:04:38

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

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

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

preg_replace('/(text1)text2(text3)/is','$1$2',$html);
风启觞 2024-10-23 01:04:38

还有一种替代方法可以在匹配模式中使用 text1text3,然后通过替换字符串将它们放回。您可以像这样使用断言:

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

这样,正则表达式仅查找存在的情况,但在应用替换时不会考虑这两个字符串。

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

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);

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.

只是在用心讲痛 2024-10-23 01:04:38

试试这个:

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

希望它有效!

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

Try this:

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

Hope it works!

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

兔姬 2024-10-23 01:04:38

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

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

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文