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