I use the following pattern to match and replace a simple IF-ELSE-ENDIF block using preg_replace_callback:
##IF (.*?)##(.*?)(?:##ELSE##(.*?))?##ENDIF##
The following two examples are matched and replaced correctly
1. ##IF x()## foo ##ENDIF##
Result:
Group 1: `x()`
Group 2: ` foo `
2. ##IF y()## foo ##ELSE## bar ##ENDIF##
Result:
Group 1: `y()`
Group 2: ` foo `
Group 3: ` bar `
Now I want to enhance this functionality to allow nested IF-ELSE blocks, e.g.
##IF g()## pre-outer-if ##IF h()## inner-if ##ENDIF## post-outer-if ##ELSE## outer-else ##ENDIF##
Here is a demo on regex101.com.
I played around to enhance the pattern with the recursion operator and positive lookaheads but I did not succeed. The goal is to match and replace related IF-ELSE-ENDIF blocks to allow a user to define conditional textblocks.
If possible, I want to avoid writing a language parser for this enhancement.
Thanks a lot for any suggestion!
preg_replace_callback.