解决方案 »

  1.   

    <?php$realcontent = file_get_contents("template_test.html");
    $tpl_string = <<< TEMPLEATE
    <html>
        <head>
            <title>{\$title}</title>
            <meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
        </head>
        <body>
            <div>作者:{\$name}</div>
            <div>国家:{\$china}</div>
            <div>省份:{\$provice}</div>
            <div>城市:{\$city}</div>
        </body>
    </html>
    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();
    ?>
      

  2.   

    smarty 3 以后默认不支持PHP 混写了 换成 smarty 2 就可以了
      

  3.   

    你只产生了 php 代码,并没有执行他