且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

PHP正则表达式用[]替换嵌套的()

更新时间:2023-02-26 20:48:03

使用正则表达式无法可靠地做到这一点.如果您无论如何都选择使用这种方法,答案取决于您愿意对输入做出哪些假设.例如,如果您愿意假设最里面的括号可以被替换,那么答案很简单:

You can't do this reliably with regular expressions. If you choose to go with this method anyway, the answer depends on what assumptions you're willing to make about the input. If, for example, you're willing to assume the innermost parentheses can be replaced, the answer is easy:

preg_replace('!\(([^()]*)\)!', '{$1}', $input);

如果您专门寻找嵌套括号,请尝试:

If you're specifically looking for nested parentheses, try:

preg_replace('!\(([^()]*)\(([^()]*)\)([^()]*)\)!', '($1{$2}$3)', $input);