After about two hours of trying, "Googling", "PHP Builder Board Searchiung", I finally succeded to do what's written in the topic...
Before I explain, please do not talk about Smarty. I know it, but since I'm crazy, I like to build my own stuff... 😛
I'm building a template system in PHP and variables use the following syntax :
{#variable name#}
I wanted to add a foreach thing, so my system can loop through a part of the actual template. I wanted this to allow nested foreach's, just in case...
So, I wanted something like this...
Code :
foreach associated with variable 1
Contents part 1-1
foreach associated with variable 2
Contents part 2
end of foreach
Contents part 1-2
end of foreach
So "Contents part 2" has to be parsed first (output is called, let's say, Output A), then "Contents part 1-1", "Output A" and "Contents part 1-2" are parsed...
My owns tags for this are :
Opening tag :
{#:FOREACH:variable name#}
Closing tag :
{#:XFOREACH}
So, I finally wrote this... please note that at the moment it only replaced "Contents part 2" because I didn't add the while(preg_match(...)) { ... } because my brain's off...
<?
$strOuverture_1 = preg_quote('{#:FOREACH:', '/');
$strOuverture_2 = preg_quote('#}', '/');
$strFermeture = preg_quote('{#:XFOREACH#}', '/');
$strMotif = sprintf('/%s([^#])*?%s((?:(?!%s).)*?)%s/s', $strOuverture_1, $strOuverture_2, ($strOuverture_1) ,$strFermeture);
$strTest = '-1- {#:FOREACH:A#} -1-
-2- {#:FOREACH:B#} -2-
B.Content is {#B:Content#}
-x2- {#:XFOREACH#} -x2-
-x1-{#:XFOREACH#}-x1-';
echo '<pre>';
function test($arrParties) {
return sprintf('<span style="font-style:italic;">Let\'s use the variable «%s» with the following contents : «%s»</span>', $arrParties[1], $arrParties[2]);
}
echo preg_replace_callback($strMotif, 'test', $strTest);
?>
And yes, that's in French, so have fun translating ! 😉