PHP regular expression to replace nested () with []

前端 未结 5 1236
感动是毒
感动是毒 2021-01-21 23:25

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 t

5条回答
  •  余生分开走
    2021-01-21 23:57

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

提交回复
热议问题