Php 删除包含特定单词-regex的括号
我目前正在使用正则表达式从字符串中删除括号。它工作良好,甚至可以应用于嵌套括号。但是,有时我不想删除括号及其内容。如何仅删除包含单词Php 删除包含特定单词-regex的括号,php,regex,Php,Regex,我目前正在使用正则表达式从字符串中删除括号。它工作良好,甚至可以应用于嵌套括号。但是,有时我不想删除括号及其内容。如何仅删除包含单词remove.的括号(及其内容),并保留其他括号 $string = "ABC (test. blah blah) outside (remove. take out)"; echo preg_replace("/\(([^()]*+|(?R))*\)/","", $string); 试试这个正则表达式: [(](?![^)]*?remove)([^)]+)[)]
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)([^)]+)[)]
要匹配具有删除文本的内容。改为查看=
代码>
对于php
code,它应该是:
$input = "ABC (test. blah blah) outside (remove. take out)";
ECHO preg_replace("/[(](?=[^)]*?remove)([^)]+)[)]/", "$1", $input);
希望有帮助。不确定“替换为$1
”是什么意思,可以用php代码修改吗?谢谢,太好了。有两个额外的空间吗?格式化后,它会留下两个spaces@MaryCoding. 是的,只需在正则表达式的末尾添加\s?
。