删除包含某个单词的括号 - 正则表达式
问题描述:
我目前使用正则表达式从字符串中删除括号。它运行良好,甚至可以应用于嵌套括号。但是,有时候我不想删除括号及其内容。如何删除包含单词remove.
的括号(及其内容)并保留其他括号?删除包含某个单词的括号 - 正则表达式
$string = "ABC (test. blah blah) outside (remove. take out)";
echo preg_replace("/\(([^()]*+|(?R))*\)/","", $string);
答
试试这个正则表达式:
[(](?![^)]*?remove)([^)]+)[)]
而且通过$1
更换。
解释:
[(] # the initial '('
(?! # don't match if in sequence is found:
[^)]*? # before the closing ')'
remove # the 'remove' text
) #
([^)]+) # then, save/group everything till the closing ')'
[)] # and the closing ')' itself
希望它能帮助。
或者简单:
[(](?=[^)]*?remove)([^)]+)[)]
要匹配那些有remove
文本。看起来=
而不是!
。
随着php
代码,它应该是:
$input = "ABC (test. blah blah) outside (remove. take out)";
ECHO preg_replace("/[(](?=[^)]*?remove)([^)]+)[)]/", "$1", $input);
希望它能帮助。
不确定你的意思是“用$ 1替换”你能用php代码修改吗?谢谢。 – MaryCoding
完美。有两个删除额外的空间吗?格式化后,它留下双空格 – MaryCoding
@MaryCoding。是的,只需在正则表达式的末尾添加'\ s?'。 – 2015-10-17 00:31:11