时间:2021-07-01 10:21:17 帮助过:33人阅读
$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();
?>