smarty就是一个类php
例1:自定义smarty搜索引擎,认识smartyhtml
这段正则表达式:\s*表空格,{}须要转义 ([a-zA-Z_][a-zA-Z0-9_]*) 以字母或者下划线开始,后面能够是字母数字下划线,*0或多个字符正则表达式
生成的组合文件:数据库
显示的结果:ide
源代码:以下ui
sm.htmlthis
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<title>{$title}</title>
</head>
<body>
<div> {$xx}</div>
<div> {$xx}</div>
<div> {$title}</div>
<div> {$xx}</div>
<div> {$xx}</div>
<div> {$xx}</div>搜索引擎
</body>
</html>3d
sm.phphtm
<?php
include "smarty.class.php";
$sm = new smarty();
//例如:链接数据库,获取如下内容;
$tt = " this is article title";
$xinxi = "this is the article content";
$sm ->assign("title",$tt);
$sm ->assign("xx",$xinxi);
$sm ->display("sm.html");
//var_dump($sm);
smarty.class.php
<?php class smarty{ private $vars=array(); function assign($key,$value) { $this->vars[$key] = $value; } function display($tplfile) { $tfile ="./tpls/".$tplfile; $comfile = "./coms/com_".$tplfile.".php"; if(!file_exists($comfile) || filemtime($comfile) < filemtime($tfile) ) { $content = file_get_contents($tfile); $pattern =array( '/\{\s*\$([a-zA-Z_][a-zA-Z0-9_]*)\s*\}/' ); $replacement = array( '<?php echo $this->vars["${1}"]; ?>' ); $newcontent = preg_replace($pattern, $replacement, $content); file_put_contents($comfile,$newcontent); } include $comfile; } }