smarty就是一个类

认识smarty

认识smarty

认识smarty

例1:自定义smarty搜索引擎,认识smarty

认识smarty

认识smarty

认识smarty

这段正则表达式:\s*表空格,{}需要转义  ([a-zA-Z_][a-zA-Z0-9_]*)  以字母或者下划线开始,后面可以是字母数字下划线,*0或多个字符

生成的组合文件:

认识smarty

显示的结果:

认识smarty

源代码:如下

sm.html

<!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>

sm.php

<?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;    
    }    
}