Tek-Tips is the largest IT community on the Internet today!

Members share and learn making Tek-Tips Forums the best source of peer-reviewed technical information on the Internet!

  • Congratulations SkipVought on being selected by the Tek-Tips community for having the most helpful posts in the forums last week. Way to Go!

Parssing Template Nested Ifs

Status
Not open for further replies.

stakadush

Programmer
Oct 1, 2001
195
0
0
IL
Hey :)

i have programmed a template system for a project i am working on. i am having problems when the template has nested ifs inside it. i can't think of a way to parse those ifs correctly.
here is an example (my template system tags are enclosed in %%):

%if_login%
user logged in
%if_user_admin%
you are an admin! welcome....
%end_if%

here is some more text in case the user has logged in.....
%else%
%if_logoff%
you logged off succesfully!
%end_if%

you need to login...
print login form here....
%end_if%

now the problem is i was trying to use the following regular expression to process the if statements:
$my_pattern = preg_replace("/%if_([^%]+)%(.*?)(?:%else%(.*?)|)%end_if%/ise", "\$this->process_if('\\1', '\\2', '\\3', \$iterate)", $my_pattern);

it works well if there are no nested ifs, but when it encounters a nested if, it takes the wrong %end_if% and all gets mixed up...i wanted to have a function that will not mind the number of if statements...
i tried using preg_split to split as follwos: preg_split('/(%(?:if_[^%]+|else)%)(.*?)/is',$data, -1, PREG_SPLIT_DELIM_CAPTURE | PREG_SPLIT_NO_EMPTY);

and then looping on that but i am totally stuck! my head went blank...;)

any ideas on how to crack this one?!

cheers!

(-:
 
You'll want to think about recursion - a function that can call itself.

Your regular expression is doing its job in finding exactly what you are looking for, but as you noticed, it works in a linear fashion, not in an embedded fashion.

You might want to think about finding the first if, and then calling the same function over again with the rest of the code after the if. Once it begins to encounter the else and end ifs, it works it way out backwards from the recursive functions.

There are whole semester Computer Science classes taught on just parsing and syntax algorithms.
 
Status
Not open for further replies.

Part and Inventory Search

Sponsor

Back
Top