$realcontent =$this->filecontent;
$mode = '/\{\$([\w]+)\}/';
if(preg_match($mode,$realcontent)){
var_dump($assign_vars);
$realcontent=preg_replace($mode,"<?php echo \$this->assign_vars['$1'] ?>",$realcontent); ;//替换成index.php文件中注入的变量
}
return $realcontent;
}
运行后代码为
<?php echo $this->assign_vars['content'] ?>
作者:<?php echo $this->assign_vars['name'] ?><?php echo $this->assign_vars['var'] ?>
回复讨论(解决方案)
<?php$realcontent = file_get_contents("template_test.html");$tpl_string = <<< TEMPLEATE{\$title} 作者:{\$name} 国家:{\$china} 省份:{\$provice} 城市:{\$city} TEMPLEATE;$mode = '/\{\$(\w+)\}/';$assign_arr = array();function assign($name, $value) { global $assign_arr; $assign_arr[$name] = empty($value) ? '' : $value; return $assign_arr;}function replace_content($match) { global $assign_arr; if (!empty($match)) { return array_key_exists($match[1], $assign_arr) ? $assign_arr[$match[1]] : ''; }}assign("title", "I love you");assign("name", "iseagold");assign("china", "中国");assign("provice", "广东省");assign("city", "深圳市");assign("no", "页面不存在,未取出的变量");echo preg_replace_callback($mode, "replace_content", $tpl_string);//===================================简单的类版本==========================================================class Template { public $assign_items = array(); public $content; function __construct($file) { $this->content = file_get_contents($file); } function assign($name, $value) { $this->assign_items[$name] = empty($value) ? "" : $value; } function replace() { $arr_assign_items = array(); $content = ''; $content = $this->content; $arr_assign_items = $this->assign_items; $pattern = '/\{\$(\w+)\}/'; $this->content = preg_replace_callback($pattern, function($match) use($arr_assign_items) { if (!empty($match)) { if (array_key_exists($match[1], $arr_assign_items)) { echo $arr_assign_items[$match[1]]; return $arr_assign_items[$match[1]]; } } }, $content); } function display() { echo $this->content; }}$template = new Template("template_test.html");$template->assign("title", "I love you");$template->assign("name", "iseagold");$template->assign("china", "中国");$template->assign("provice", "广东省");$template->assign("city", "深圳市");$template->assign("no", "页面不存在,未取出的变量");$template->replace();$template->display();?>
smarty 3 以后默认不支持PHP 混写了 换成 smarty 2 就可以了
笔误了, 是模仿写 ,不是默写...
笔误了, 是模仿写 ,不是默写...
把那个编译类看懂,全是正则
你只产生了 php 代码,并没有执行他