欧美bbbwbbbw肥妇,免费乱码人妻系列日韩,一级黄片

php模板函數(shù) 正則實(shí)現(xiàn)代碼

 更新時(shí)間:2012年10月15日 01:19:59   作者:  
有些空閑,就弄了下template函數(shù),比較粗糙。主要是利用正則表達(dá)式,把模板文件(html文件)轉(zhuǎn)換成php文件,從而實(shí)現(xiàn)前后臺(tái)分離,即是所謂的mvc思想了
我看過(guò)phpcms、discuz的源碼,所以可能就缺乏創(chuàng)新了,不過(guò)原理大都相通,只是細(xì)節(jié)處理可能稍微不同。
說(shuō)正題,下面開(kāi)始談?wù)劸唧w實(shí)現(xiàn)過(guò)程了。
1.首先要想好模板文件放在哪?轉(zhuǎn)換后的php文件放哪?還有怎么命名?直接上源碼:
復(fù)制代碼 代碼如下:

function template($tpl = 'index',$dir = 'hello')
{
if(!file_exists($pd = TPL_PATH.$dir.'/'))@mkdir($pd,0777) or die("$pd目錄創(chuàng)建失敗");//如cache/tpl/hello/
if(!file_exists($td = TPL.$dir.'/'))@mkdir($td,0777) or die("$td目錄創(chuàng)建失敗");//如data/tpl/hello/

$t2p = $pd.$tpl.'.php';//模板文件正則轉(zhuǎn)換后形成的php文件,如cache/tpl/hello/index.php
$t2h = $td.$tpl.'.html';//html模板文件,如data/tpl/hello/index.html

2.什么時(shí)候需要正則轉(zhuǎn)換?可以是正則后的php文件不存在,或正則前的html文件發(fā)生改變時(shí)。這里使用到了filemtime(string $path)函數(shù),其返回文件最近修改時(shí)間。
復(fù)制代碼 代碼如下:

if(!file_exists($t2p) || @filemtime($t2p) < @filemtime($t2h) )//模板文件改變后,正則的php文件相應(yīng)更新
{
template_go($t2p,$t2h);//模板轉(zhuǎn)換開(kāi)始
}
return $t2p;//返回正則后的php文件,可以這樣調(diào)用:如include template('header','hello');
}

3.開(kāi)始模板轉(zhuǎn)換,先從html文件中讀出,然后正則替換,最后寫(xiě)入php文件中。
復(fù)制代碼 代碼如下:

function template_go($t2p,$t2h)
{
$str = @file_get_contents($t2h);//讀出
if($str === false) exit("模板文件缺失,請(qǐng)檢查!");
$str = template_do($str);//正則替換
@chmod($t2p,0777);
return $str = file_put_contents($t2p, $str);//寫(xiě)入
}

4.正則規(guī)則,幾條比較簡(jiǎn)略的正則替換語(yǔ)法。
復(fù)制代碼 代碼如下:

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,要考慮多次進(jìn)行該正則而換行的問(wèn)題*/
$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 "\\1"; ?>', $str);/*{include xx.php}換成<?php include xx.php ?> */
$str = "<?php defined('IN_PH') or die('Access Denied');?>".$str;
//$str = preg_replace('/\s+/', ' ', $str);//查看網(wǎng)頁(yè)源代碼看看
return $str;
}

當(dāng)然,這個(gè)函數(shù)現(xiàn)在還是比較簡(jiǎn)陋的,期待能完善它。
ps:這算是我第一次寫(xiě)博客,原本是想著有空的話(huà)就寫(xiě)寫(xiě)技術(shù)博客,談?wù)勑牡?,?dāng)總結(jié)經(jīng)驗(yàn)教訓(xùn)了,同時(shí)也是向大牛們學(xué)習(xí)。
還有就是,博客還是比較好保存的,方便省事,呵呵。

相關(guān)文章

最新評(píng)論