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;
?>
热门推荐
2 医政科祝福语简短
10 许嵩生日祝福语简短
11 异性朋友简短生日祝福语
12 上嫂子生日祝福语简短
13 喜事敬酒祝福语简短精辟
14 简短大气的狗年祝福语
15 近代生日祝福语简短精辟
16 婚礼祝福语简短精辟的
17 订婚祝福语简短好听女
18 别人生辰祝福语简短