温馨提示×

温馨提示×

您好,登录后才能下订单哦!

密码登录×
登录注册×
其他方式登录
点击 登录注册 即表示同意《亿速云用户服务条款》

怎么在php中利用正则表达式实现一个模板函数

发布时间:2021-01-30 10:00:24 来源:亿速云 阅读:133 作者:Leah 栏目:开发技术

今天就跟大家聊聊有关怎么在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 "\\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;
}

看完上述内容,你们对怎么在php中利用正则表达式实现一个模板函数有进一步的了解吗?如果还想了解更多知识或者相关内容,请关注亿速云行业资讯频道,感谢大家的支持。

向AI问一下细节

免责声明:本站发布的内容(图片、视频和文字)以原创、转载和分享为主,文章观点不代表本网站立场,如果涉及侵权请联系站长邮箱:is@yisu.com进行举报,并提供相关证据,一经查实,将立刻删除涉嫌侵权内容。

AI