php模板函数的正则实现代码

php中文网
发布: 2016-07-25 09:03:25
原创
1119人浏览过
  1. function template($tpl = 'index',$dir = 'hello')

  2. {
  3. if(!file_exists($pd = tpl_path.$dir.'/'))@mkdir($pd,0777) or die("$pd目录创建失败");//如cache/tpl/hello/
  4. if(!file_exists($td = tpl.$dir.'/'))@mkdir($td,0777) or die("$td目录创建失败");//如data/tpl/hello/
  5. $t2p = $pd.$tpl.'.php';//模板文件正则转换后形成的php文件,如cache/tpl/hello/index.php

  6. $t2h = $td.$tpl.'.html';//html模板文件,如data/tpl/hello/index.html
  7. ?>
复制代码

2.什么时候需要正则转换?可以是正则后的php文件不存在,或正则前的html文件发生改变时。这里使用到了filemtime(string $path)函数,其返回文件最近修改时间。

  1. if(!file_exists($t2p) || @filemtime($t2p) {
  2. template_go($t2p,$t2h);//模板转换开始
  3. }
  4. return $t2p;//返回正则后的php文件,可以这样调用:如include template('header','hello');
  5. }
  6. ?>
复制代码

3.开始模板转换,先从html文件中读出,然后正则替换,最后写入php文件中。

  1. function template_go($t2p,$t2h)
  2. {
  3. $str = @file_get_contents($t2h);//读出
  4. if($str === false) exit("模板文件缺失,请检查!");
  5. $str = template_do($str);//正则替换
  6. @chmod($t2p,0777);
  7. return $str = file_put_contents($t2p, $str);//写入
  8. }
  9. ?>
复制代码

4.正则规则,几条比较简略的正则替换语法。

  1. function template_do($str)
  2. {
  3. $str = preg_replace('/([ +]) +/s', '\1', $str);//去掉TAB制表符。修正符/s是不忽略换行
  4. $str = preg_replace('/{$(.*)}/Us', '', $str);/*{$xx}换成 注意,必须加上修正符/U,只能匹配一次。也可懒惰匹配*/
  5. $str = preg_replace('/{php (.+)}/', '', $str);/*{php xxxx}换成 注意,不能加上修正符/s,要考虑多次进行该正则而换行的问题*/
  6. $str = preg_replace('/{template(.*)}/Us', '', $str);
  7. /*{template(xx,yy)}换成 */
  8. $str = preg_replace('/{include (.*)}/Us', '', $str);/*{include xx.php}换成 */
  9. $str = "".$str;
  10. //$str = preg_replace('/s+/', ' ', $str);//查看网页源代码看看
  11. return $str;
  12. }
  13. ?>
复制代码

当然,这个函数比较简单,期待能完善它。



PHP速学教程(入门到精通)
PHP速学教程(入门到精通)

PHP怎么学习?PHP怎么入门?PHP在哪学?PHP怎么学才快?不用担心,这里为大家提供了PHP速学教程(入门到精通),有需要的小伙伴保存下载就能学习啦!

下载
来源:php中文网
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系admin@php.cn
最新问题
开源免费商场系统广告
热门教程
更多>
最新下载
更多>
网站特效
网站源码
网站素材
前端模板
关于我们 免责申明 意见反馈 讲师合作 广告合作 最新更新
php中文网:公益在线php培训,帮助PHP学习者快速成长!
关注服务号 技术交流群
PHP中文网订阅号
每天精选资源文章推送
PHP中文网APP
随时随地碎片化学习
PHP中文网抖音号
发现有趣的

Copyright 2014-2025 https://www.php.cn/ All Rights Reserved | php.cn | 湘ICP备2023035733号