復制代碼 代碼如下:
function template($tpl = 'index',$dir = 'hello')
{
if(!file_exists($pd = TPL_PATH.$dir.'/'))@mkdir($pd,0777) or die("$pd目錄創建失敗");//如cache/tpl/hello/
if(!file_exists($td = TPL.$dir.'/'))@mkdir($td,0777) or die("$td目錄創建失敗");//如data/tpl/hello/
$t2p = $pd.$tpl.'.php';//模板文件正則轉換后形成的php文件,如cache/tpl/hello/index.php
$t2h = $td.$tpl.'.html';//html模板文件,如data/tpl/hello/index.html
復制代碼 代碼如下:
if(!file_exists($t2p) || @filemtime($t2p) < @filemtime($t2h) )//模板文件改變后,正則的php文件相應更新
{
template_go($t2p,$t2h);//模板轉換開始
}
return $t2p;//返回正則后的php文件,可以這樣調用:如include template('header','hello');
}
復制代碼 代碼如下:
function template_go($t2p,$t2h)
{
$str = @file_get_contents($t2h);//讀出
if($str === false) exit("模板文件缺失,請檢查!");
$str = template_do($str);//正則替換
@chmod($t2p,0777);
return $str = file_put_contents($t2p, $str);//寫入
}
復制代碼 代碼如下:
function template_do($str)
{
$str = preg_replace('/([/n/r+])/t+/s', '//1', $str);//去掉TAB制表符。修正符/s是不忽略換行
$str = preg_replace('//{/$(.*)/}/Us', '<?php echo $//1; ?>', $str);/*{$xx}換成<?php echo $xx;?> 注意,必須加上修正符/U,只能匹配一次。也可懶惰匹配*/
$str = preg_replace('//{php (.+)/}/', '<?php //1 ?>', $str);/*{php xxxx}換成<?php xxxx ?> 注意,不能加上修正符/s,要考慮多次進行該正則而換行的問題*/
$str = preg_replace('//{template(.*)/}/Us', '<?php include template//1; ?>', $str);
/*{template(xx,yy)}換成<?php include template(xx,yy); ?> */
$str = preg_replace('//{include (.*)/}/Us', '<?php include "http://1"; ?>', $str);/*{include xx.php}換成<?php include xx.php ?> */
$str = "<?php defined('IN_PH') or die('Access Denied');?>".$str;
//$str = preg_replace('//s+/', ' ', $str);//查看網頁源代碼看看
return $str;
}
新聞熱點
疑難解答