正则表达式仅在标签内删除所有出现的字符串

编程入门 行业动态 更新时间:2024-10-23 16:23:52
本文介绍了正则表达式仅在标签内删除所有出现的字符串的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧! 问题描述

我需要删除所有出现的字符串,但前提是它在 2 个标签内.

I need to remove all occurances of a string but only when it is within 2 tags.

例如在下面的内容中,我需要删除 [bar][/bar] 标签中出现的两个 foo.

For example in the content below I need to remove both occurances of foo within the [bar][/bar] tags.

foo foo [bar] foo bar foo [/bar] foo

我正在使用 PHP,我想找到一个不涉及 2 个步骤的解决方案(即首先搜索 [bar][/bar] 之间的内容,然后进行替换).如果这是不可能的,那么没问题,非常感谢您的帮助!

I am using PHP and I would like to find a solution which doesn't involve 2 steps (ie search for the content between [bar][/bar] first and then do the replace). If this is not possible then no problem, any help is much appreciated!

推荐答案

如果你的标签都格式正确且没有嵌套,你可能会成功

If your tags are all well formed and not nested you may be successful with this

\bfoo\b(?=[^\[]*\[\/bar\])

查看在Regexr上

它搜索由单词边界\b包围的foo(foobar中的foo将不匹配),后跟一个结束标记[/bar].为确保没有新的开始标记,我只会将 [ 以外的字符与 [^\[]* 匹配.

It searches for foo surrounded by word boundaries \b (foo in foobar will not match), that is followed by a closing tag [/bar]. to ensure that there is no new opening tag I will only match characters other than [ with [^\[]*.

(?=[^\[]*\[\/bar\]) 是一个前瞻断言,它不匹配它只在里面的模式遵循时向前看.

(?=[^\[]*\[\/bar\]) is a lookahead assertion that does not match it only looks ahead if the pattern inside is following.

更多推荐

正则表达式仅在标签内删除所有出现的字符串

本文发布于:2023-10-23 13:49:45,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/jswz/34/1521004.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:字符串   标签   正则表达式

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!