我一直在使用此 /\(\s*([^)]+?)\s*\)/
正则表达式通过 PHP preg_replace 函数删除外括号(阅读我之前的更多内容问题 Regex to match any character except trailing spaces )。
当只有一对括号时这工作正常,但问题是当有更多时,例如 ( test1 t3() test2)
变成 test1 t3( test2)
而不是 test1 t3() test2
。
我知道正则表达式的限制,但如果我能让它不匹配任何东西,如果有超过一对括号,那就太好了。
因此,示例行为就足够了:
( 测试1 测试2 )
=> 测试1 测试2
( test1 t3() test2 )
=> (test1 t3() test2)
编辑:
我想继续修剪已删除括号内的尾随空格。
最佳答案
您可以使用这种基于递归正则表达式的代码,它也适用于嵌套括号。唯一的条件是括号应该是平衡的。
$arr = array('Foo ( test1 test2 )', 'Bar ( test1 t3() test2 )', 'Baz ((("Fdsfds")))');
foreach($arr as $str)
echo "'$str' => " .
preg_replace('/ \( \s* ( ( [^()]*? | (?R) )* ) \s* \) /x', '$1', $str) . "\n";
输出:
'Foo ( test1 test2 )' => 'Foo test1 test2'
'Bar ( test1 t3() test2 )' => 'Bar test1 t3() test2'
'Baz ((("Fdsfds")))' => 'Baz (("Fdsfds"))'
关于php - 正则表达式删除外括号,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/10766387/