开发者

How to make own simple, fast and secure PHP template without eval()?

How to make own s开发者_如何学运维imple, fast and secure PHP MySQL template without eval() for MySQL record:

+--------------------------------------------------------------+
|  id | content                                                |
|--------------------------------------------------------------|
|  12 | Today is {date}<br />Current time {include 'time.php'} |
+--------------------------------------------------------------+

{date} must return echo date('l'); and time.php content is <?php echo date('h:i A'); ?>

Expected result would be:

Today is Thursday

Current time 23:17 PM


You can search your text with a regex, you can also use replace methods to have the desired effect.

To build a complicated template engine I would refer to twig or Smarty (or another) and see how they do it.


It's possible trough preg_replace. Example for include:

function finclude($file){
    return include($file);
}

$str = "Today is {include 'date.php'}.";
echo preg_replace("/\{include '(.*)\'}/e", 'finclude("$1")', $str);

date.php:

<?php return date('jS \of F'); ?>, 2011

will return: Today is 20th of July.

Does anyone knows some better way (secure, speed performance) to do it without /e eval?

0

上一篇:

下一篇:

精彩评论

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

最新问答

问答排行榜