PHP正则表达式用[]替换嵌套的() [英] PHP regular expression to replace nested () with []

查看:45
本文介绍了PHP正则表达式用[]替换嵌套的()的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试匹配一个字符串,请参见示例,这样嵌套的括号 () 被替换为 [],以免在其他地方破坏解析器.在这种情况下,我想将 $myStr 替换为Arman; Dario (10040 Druento (Turin), IT)"...

I am trying to match a string, see example, such that a nested parantheses () is replaced by [] so to not break a parser somewhere else. In this case, I would like to replace the $myStr with "Arman; Dario (10040 Druento (Turin), IT)" ...

提前致谢!

蒙特

{x:

  $myStr = "Arman; Dario (10040 Druento (Turin), IT)";
    $pattern = "/(\()([a-z,A-Z0-9_\&\/\'\-\,\;\:\.\s^\)]+)(\))/";
    if (preg_match_all($pattern,$myStr,$matches))
        {
            print_r($matches);
        }

显然,我也需要切换match_all来替换.

Obviously, I also need to switch match_all to replace.

总结:

输入

$myStr = "Arman; Dario (10040 Druento (Turin), IT)";

输出

$myStr = "Arman; Dario (10040 Druento [Turin], IT)";

推荐答案

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

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);

这篇关于PHP正则表达式用[]替换嵌套的()的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆