里面无非就是用正则替换了相对应的语法规则。需要的同学可以拿去看看。
<?php private function compile($tpl_file = null) { ob_start(); if(empty($tpl_file)) { $tpl_file = $this->tpl_file; } //check template file exists $tpl_file = $this->config['template_dir'].$tpl_file; if(!file_exists($tpl_file) || empty($tpl_file)) { die('temlate file no found : '.$tpl_file); } else { $tpl_str = file_get_contents($tpl_file); } //compile sub template file while(preg_match('//ies', $tpl_str, $var)) { $sub_tpl_str = $this->compile($var[1]); $tpl_str = str_replace($var[0], $sub_tpl_str, $tpl_str); } //{$obj} $tpl_str = preg_replace('/\{\s*(\$[a-zA-Z0-9_.]+)\s*\}/is', "", $tpl_str); $tpl_str = preg_replace('//is', "", $tpl_str); $tpl_str = preg_replace('//ies', "''", $tpl_str); $tpl_str = preg_replace('//is', "", $tpl_str); $tpl_str = preg_replace('//is', "", $tpl_str); $tpl_str = preg_replace('//is', "", $tpl_str); // if(preg_match_all('//ies', $tpl_str, $var)) { $loop_head_str = ' $loop_head_str .= '$ROW_INDEX = 0;'; $loop_head_str .= 'foreach('.$var[1][0].' as '.$var[2][0].'){ $ROW_INDEX++; $ROW_BIT=!($ROW_INDEX%2); $tpl_str = preg_replace('//ies', "'$loop_head_str'", $tpl_str); } // if(preg_match_all('//ies', $tpl_str, $var)){ $loop_head_str = ' $loop_head_str .= '$ROW_INDEX = 0;'; $loop_head_str .= 'foreach('.$var[1][0].' as '.$var[2][0].'=>'.$var[3][0].'){ $ROW_INDEX++; $ROW_BIT=!($ROW_INDEX%2); ?>'; $tpl_str = preg_replace('//ies', "'$loop_head_str'", $tpl_str); } //$var.property.subproperty if(!function_exists('subvar')) { function subvar($str) { if(!empty($str)) { $var_list = explode('.', substr($str, 1)); foreach($var_list as $var) { $var_str .= "['$var']"; } return $var_str; } } } //$var.property.subproperty $tpl_str = preg_replace('/(<\?php+.*?\$[a-zA-Z0-9_]+)([\.a-zA-Z0-9_]*)/ies', "stripslashes('\${1}').subvar('\${2}')", $tpl_str); ob_end_flush(); return $tpl_str; } ?>