删除包含特定正则表达式的括号


Remove parenthesis that contain certain word - regex

我目前正在使用正则表达式从字符串中删除括号。它工作得很好,甚至可以应用于嵌套括号。然而,有些时候我不想删除括号和它的内容。如何仅删除包含单词remove.的括号(及其内容)并保留其他括号?

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

试试这个regex:

[(](?![^)]*?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);

希望能有所帮助。