php - 正则表达式删除外括号

标签 php regex preg-replace brackets

我一直在使用此 /\(\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/

相关文章:

php - preg_replace 问题

php - strip_tags : strip off the messy tags and styles

javascript - "[^]"正则表达式模式是什么意思(javascript 正则表达式)?

javascript - 在下拉列表中显示数组

php - 在 PHP 脚本中,在连接/发送查询到数据库时应该如何处理异常?

php - Ratchet PHP Websocket 库工作正常,但运行几天后导致 HTTP 代码 503 服务不可用

python - 在数据框中查找具有日期模式的所有列

javascript - 在 jupyter 笔记本中使用匹配替换查找和替换实用程序

php - preg_replace() 在 MySQL 表中查找匹配项

javascript - Webix 数据表 ||加载数据服务器端