I want to match the if else statements from a smarty template. And insert there my own tags. In my example <OPEN>
and </CLOSE>
.
Here is my code:
$value =
<<<SMARTY
{if}
text1
{if}
text2
{/if}
text3
{/if}
{if}
text1
{else}
text2
{/if}
{if}
text1
{if}
text2
{else}
text3
{/if}
text
{/if}
SMARTY;
echo filter($value);
function filter($value)
{
$pattern =
'(\{(?:if|else).*?\})'. // open
'((?:'.
'[^{]'.
'|\{(?!/?if|else)'.
'|(?R)'.
')+)'.
'(\{(?:\/if|else)\})'; // close
return preg_replace_callback('#'.$pattern.'#', 'filter_callback', $value);
}
function filter_callback($matches)
{
$m2 = $matches;
$m2[0] = preg_replace(array('/[\n\r]/','/ +/','/^ /'),array('',' ',''), $m2[0]);
$m2[2] = preg_replace(array('/[\n\r]/','/ +/','/^ /'),array('',' ',''), $m2[2]);
print_r($m2);
return $matches[1].'<OPEN>'.filter($matches[2]).'</CLOSE>'.$matches[3];
}
But it dosent work correctly.
For example I want to have the follow output:
{if}<OPEN>
text1
</CLOSE>{else}<OPEN>
text2
</CLOSE>{/if}
and
{if}<OPEN>
text1
{if}<OPEN>
text2
</CLOSE>{else}<OPEN>
text3
</CLOSE>{/if}
text
</CLOSE>{/if}
If anybody have a idea?