正则表达式仅在标签内删除所有出现的字符串 [英] Regex to remove all occurances of string only within tags

查看:41
本文介绍了正则表达式仅在标签内删除所有出现的字符串的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我需要删除所有出现的字符串,但前提是它在 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.

这篇关于正则表达式仅在标签内删除所有出现的字符串的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆