PHP正则替换函数preg_replace和preg_replace_callback使用总结
在编写PHP模板引擎工具类时,以前常用的一个正则替换函数为preg_replace(),加上正则修饰符/e,就能够执行强大的回调函数,实现模板引擎编译(其实就是字符串替换)。
详情介绍参考博文:PHP函数preg_replace()正则替换所有符合条件的字符串
应用举例如下:
<?php
/**
*模板解析类
*/
classTemplate{
publicfunctioncompile($template){
//if逻辑 $template=preg_replace("/\<\!\-\-\{if\s+(.+?)\}\-\-\>/e","\$this->ifTag('\\1')",$template);
return$template; }
/** *if标签 */ protectedfunctionifTag($str){
//$str=stripslashes($str);//去反转义
return'<?phpif('.$str.'){?>'; } }
$template='xxx<!--{if$user[\'userName\']}-->yyy<!--{if$user["password"]}-->zzz';
$tplComplier=newTemplate();
$template=$tplComplier->compile($template);
echo$template;
?>
热门推荐
10 对患者生日祝福语简短
11 结婚祝福语简短装备
12 周岁祝福语学生文案简短
13 订婚领证祝福语简短精辟
14 导师获奖祝福语大全简短
15 新婚购房祝福语简短精辟
16 牛年祝福语简短的爱人
17 送芒果的祝福语简短
18 送给学长毕业祝福语简短