php模板函數 正則實現代碼_PHP教程

來源:互聯網
上載者:User
我看過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', '', $str);/*{$xx}換成 注意,必須加上修正符/U,只能匹配一次。也可懶惰匹配*/
$str = preg_replace('/\{php (.+)\}/', '', $str);/*{php xxxx}換成 注意,不能加上修正符/s,要考慮多次進行該正則而換行的問題*/
$str = preg_replace('/\{template(.*)\}/Us', '', $str);
/*{template(xx,yy)}換成 */
$str = preg_replace('/\{include (.*)\}/Us', '', $str);/*{include xx.php}換成 */
$str = "".$str;
//$str = preg_replace('/\s+/', ' ', $str);//查看網頁原始碼看看
return $str;
}

當然,這個函數現在還是比較簡陋的,期待能完善它。
ps:這算是我第一次寫部落格,原本是想著有空的話就寫寫技術部落格,談談心得,當總結經驗教訓了,同時也是向大牛們學習。
還有就是,部落格還是比較好儲存的,方便省事,呵呵。

http://www.bkjia.com/PHPjc/326214.htmlwww.bkjia.comtruehttp://www.bkjia.com/PHPjc/326214.htmlTechArticle我看過phpcms、discuz的源碼,所以可能就缺乏創新了,不過原理大都相通,只是細節處理可能稍微不同。 說正題,下面開始談談具體實現過程...

  • 聯繫我們

    該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

    如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

    A Free Trial That Lets You Build Big!

    Start building with 50+ products and up to 12 months usage for Elastic Compute Service

    • Sales Support

      1 on 1 presale consultation

    • After-Sales Support

      24/7 Technical Support 6 Free Tickets per Quarter Faster Response

    • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.