Home  >  Article  >  php教程  >  PHP string template engine

PHP string template engine

大家讲道理
大家讲道理Original
2016-11-08 11:28:521520browse

这是一个简易的字符串模板引擎、数据库模板引擎。区别于一般基于文件模板的引擎,这里的模板是一个字符串,因此可以将模板存于数据库或其他地方,而且不是编译型引擎,没有缓存文件,因而就不涉及到目录权限问题。模板的基本原理是将模板处理成全php脚本的字符串,然后用eval执行符串。至于安全问题,因为用到eval执行模板里面的语句,因此模板代码必须是受信任的,大多数其他模板引擎也是这样吧。

// 字符串模板,懒得构造字符串,这里直接读取文件来模拟
$str = file_get_contents( 'tpl.php' );
// 首尾添加php脚本标签,使所有原样输出的html文本处于php脚本标签的中间
$str = "<?php if(1){?>{$str}<?php }?>";
// 用echo语句替换原样输出的html文本
$str = preg_replace_callback( &#39;/\?>([\s\S]+?)<\?/&#39;, function ($m)
{
    return &#39;?><?php echo "&#39; . addcslashes( $m[1], "\r\n\\\"" ) . &#39;";?><?&#39;;
}, $str );
// 去掉php脚本标签并执行标签里面的代码
eval( str_replace( array (
        &#39;<?php&#39;,
        &#39;?>&#39;
), &#39;&#39;, $str ) );
Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn