开发者

Converting tags to PHP tags using PHP

How can I change

{for ...cond.... }
somethinginbetween
{/for}

to

<?php for (...cond...){ ?>
somethinginbetween
<?php } ?&g开发者_开发问答t;


This is a quick-and-dirty string literal string replacement:

$code = str_replace('{for ', '<?php for (', $code);
$code = str_replace(' }', '){ ?>', $code);
$code = str_replace('{/for}', '<?php } ?>', $code);

It will not work if somethhingbetween contains if(){ } because } gets replaced by ){ ?>. But for other cases with just {for condition } and {/for}, it suffice.

Regular expression approach combined with simple string replacement, this assumes no occurences of } in the for loop (match everything except for }: [^}]+)

$code = preg_replace('/{for ([^}]+)}/', '<?php for ($1) { ?>', $code);
$code = str_replace('{/for}', '<?php } ?>', $code);

This function does no validating whatsoever, it's your responsibility to feed it with properly opened / closed {for} and {/for}s.

If you need to execute PHP, insert PHP. The other way would be writing your own parsing code. You could look at template projects like Smarty.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜