2015-10-17 218 views
1

我目前使用正则表达式从字符串中删除括号。它运行良好,甚至可以应用于嵌套括号。但是,有时候我不想删除括号及其内容。如何删除包含单词remove.的括号(及其内容)并保留其他括号?删除包含某个单词的括号 - 正则表达式

$string = "ABC (test. blah blah) outside (remove. take out)"; 
echo preg_replace("/\(([^()]*+|(?R))*\)/","", $string); 

回答

1

试试这个正则表达式:

[(](?![^)]*?remove)([^)]+)[)] 

而且通过$1更换。

Regex live here.

解释:

[(]   # 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文本。看起来=而不是!

Regex live here.


随着php代码,它应该是:

$input = "ABC (test. blah blah) outside (remove. take out)"; 
ECHO preg_replace("/[(](?=[^)]*?remove)([^)]+)[)]/", "$1", $input); 

希望它能帮助。

+0

不确定你的意思是“用$ 1替换”你能用php代码修改吗?谢谢。 – MaryCoding

+0

完美。有两个删除额外的空间吗?格式化后,它留下双空格 – MaryCoding

+0

@MaryCoding。是的,只需在正则表达式的末尾添加'\ s?'。 – 2015-10-17 00:31:11

相关问题