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;
?>
热门推荐
3 祝福语简短的微信
10 幼儿祝福语大全简短贺卡
11 感谢教官文案祝福语简短
12 鼠年同事祝福语简短创意
13 元旦祝福语 简短独特群发
14 妈咪跟我生日祝福语简短
15 给儿子新婚祝福语简短
16 伴娘祝福语长文案简短
17 恭喜高考完祝福语简短
18 生日祝福语送老公简短