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 好听的元旦简短祝福语