PHP regular expression to replace nested () with []

前端 未结 5 1225
感动是毒
感动是毒 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-22 00:16

    Nested parenthesis cannot be matched with a regular grammar. Therefore, a true regular expression will not be able to match nested parenthesis of an arbitrary depth. See the post Can regular expressions be used to match nested parenthesis? for a more detailed explanation.

    Thankfully, regular expressions in PHP are not actually regular. Perl "regular" expressions support recursive patterns, as described on PHP.net. For this particular problem, have you considered replacing the elements individually with str_replace()? This would only fail if you can encounter unmatched opening and closing parenthesis (e.g. (foo (bar)).

提交回复
热议问题