Reputation: 385
I'm developing a simple template engine and trying to implement my own simple syntax for handling loops and eventually if
statements rather than including PHP in my template files.
I know a lot of people will say don't bother or just use an existing system, but as it's for my dissertation I want as much of it to be my own work as possible!
Anyway, back to the problem. I've got the following code in a my template file as an example:
<p>Template Header</p>
{{foreach{array1}}}
<p>This is the first content line that should be displayed.</p>
{{/foreach}}
{{foreach{array2}}}
<p>This is the second content line that should be displayed.</p>
{{/foreach}}
<p>Template Footer</p>
I've then got the following PHP to read the file, look for loops and extract them.
<?php
$template = file_get_contents('reg.html');
$expression = "#.*{{foreach{(.*?)}}}(.*?){{/foreach}}.*#is";
$result = preg_replace($expression, "$1", $template);
var_dump($result);
?>
When calling preg_replace()
and dumping the result $1 is giving me the array name which will be used for the loop (array1 or array2), then changing it to $2 will give me the content between the loop tags. Perfect. The problem is it only works for one {{foreach}}
tag.
Is there anyway I can loop all matches of the regex to get the results I'm getting above?
Upvotes: -1
Views: 90
Reputation: 145492
$expression = "#.*{{foreach{(.*?)}}}(.*?){{/foreach}}.*#is";
^^ ^^
You are not just matching the "foreach" template tag, but also everything before and after it. That means the second foreach will get eaten up by .*
too. So you can't match it again.
Upvotes: 1