Recusrive/nesting regex for tags/templating system
Posted: Thu May 07, 2009 9:08 am
I'm trying to create a simple templating system (in PHP) with some regex involved and I've come up against a bit of a sticking point.
In my template files I have custom tags in the format:
I pull a few things from this sort of markup:
Currently I'm using a convoluted PHP loop with multiple calls to preg_match to achieve this. What I'd like is a more efficient single regex statement that can pull everything I need out. With preg_match_all, the desired result would look something like:
My main question would be if this is even possible with regex? I understand theres a recursive operator (?R) which I've been trying to get my head around but most of the examples use it as a means to find simple nested sets of brackets - '(1(2(3)4)5)' etc - so I'm not sure if it can actually be applied to this more complex task. Certainly I've been trying to plug it in to no avail, but would it ever work if I got it right or is this task just beyond regex?
I understand this might be a bit of an effort to comprehend so thanks in advance for anyone who takes the time to read it.
In my template files I have custom tags in the format:
Code: Select all
{if:$var}Var is true!{/if:$var}- The entire statement itself (to replace later)
- The name of the $var, in this case 'var' (to check for true/false)
- The content between the two tags, in this case 'Var is true!'
Code: Select all
{if:$var_1}var 1 is true! {if:$var_2}var 2 is true!{/if:$var_2} {/if:$var_1}
Currently I'm using a convoluted PHP loop with multiple calls to preg_match to achieve this. What I'd like is a more efficient single regex statement that can pull everything I need out. With preg_match_all, the desired result would look something like:
Code: Select all
Array
(
[0] => Array
(
[0] => {if:$var_1}var 1 is true! {if:$var_2}var 2 is true!{/if:$var_2} {/if:$var_1}
[1] => {if:$var_2}var 2 is true!{/if:$var_2}
)
[1] => Array
(
[0] => var_1
[1] => var_2
)
[2] => Array
(
[0] => var 1 is true! {if:$var_2}var 2 is true!{/if:$var_2}
[1] => var 2 is true!
)
)
I understand this might be a bit of an effort to comprehend so thanks in advance for anyone who takes the time to read it.