国产探花免费观看_亚洲丰满少妇自慰呻吟_97日韩有码在线_资源在线日韩欧美_一区二区精品毛片,辰东完美世界有声小说,欢乐颂第一季,yy玄幻小说排行榜完本

首頁 > 開發 > PHP > 正文

php模板函數 正則實現代碼

2024-05-04 23:13:41
字體:
來源:轉載
供稿:網友
我看過phpcms、discuz的源碼,所以可能就缺乏創新了,不過原理大都相通,只是細節處理可能稍微不同。
說正題,下面開始談談具體實現過程了。
1.首先要想好模板文件放在哪?轉換后的php文件放哪?還有怎么命名?直接上源碼:

復制代碼 代碼如下:


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


2.什么時候需要正則轉換?可以是正則后的php文件不存在,或正則前的html文件發生改變時。這里使用到了filemtime(string $path)函數,其返回文件最近修改時間。

復制代碼 代碼如下:


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


3.開始模板轉換,先從html文件中讀出,然后正則替換,最后寫入php文件中。

復制代碼 代碼如下:


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);//寫入
}


4.正則規則,幾條比較簡略的正則替換語法。

復制代碼 代碼如下:


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;
}


當然,這個函數現在還是比較簡陋的,期待能完善它。
ps:這算是我第一次寫博客,原本是想著有空的話就寫寫技術博客,談談心得,當總結經驗教訓了,同時也是向大牛們學習。
還有就是,博客還是比較好保存的,方便省事,呵呵。
發表評論 共有條評論
用戶名: 密碼:
驗證碼: 匿名發表
主站蜘蛛池模板: 青神县| 仁寿县| 肃北| 高密市| 云阳县| 锡林郭勒盟| 兴和县| 永修县| 都匀市| 和龙市| 太湖县| 宿松县| 嘉定区| 镇坪县| 中超| 华阴市| 丽水市| 柳州市| 乌恰县| 平昌县| 钟山县| 罗定市| 南京市| 安丘市| 红原县| 和政县| 南昌县| 无为县| 新巴尔虎右旗| 从化市| 长垣县| 三河市| 微博| 张北县| 纳雍县| 聂荣县| 广南县| 大悟县| 平利县| 巴彦淖尔市| 青川县|