自个儿默写smarty模板引擎,不解析php呢(求高手帮忙)
程序员文章站
2022-05-18 15:27:33
...
自己默写smarty模板引擎,不解析php呢(求高手帮忙)
$realcontent =$this->filecontent;
$mode = '/\{\$([\w]+)\}/';
if(preg_match($mode,$realcontent)){
var_dump($assign_vars);
$realcontent=preg_replace($mode,"assign_vars['$1'] ?>",$realcontent); ;//替换成index.php文件中注入的变量
}
return $realcontent;
}
运行后代码为
assign_vars['content'] ?>
作者:assign_vars['name'] ?>assign_vars['var'] ?>
------解决思路----------------------
------解决思路----------------------
你只产生了 php 代码,并没有执行他
$realcontent =$this->filecontent;
$mode = '/\{\$([\w]+)\}/';
if(preg_match($mode,$realcontent)){
var_dump($assign_vars);
$realcontent=preg_replace($mode,"assign_vars['$1'] ?>",$realcontent); ;//替换成index.php文件中注入的变量
}
return $realcontent;
}
运行后代码为
assign_vars['content'] ?>
作者:assign_vars['name'] ?>assign_vars['var'] ?>
------解决思路----------------------
$realcontent = file_get_contents("template_test.html");
$tpl_string ={\$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();
?>
------解决思路----------------------
你只产生了 php 代码,并没有执行他
相关文章
相关视频