我目前正在使用正则表达式从字符串中删除括号。它工作得很好,甚至可以应用于嵌套括号。然而,有些时候我不想删除括号和它的内容。如何仅删除包含单词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);
希望能有所帮助。