这篇文章主要介绍了PHP正则替换函数preg_replace和preg_replace_callback使用总结,本文是在写一个模板引擎遇到一来源gao@dai!ma.com搞$代^码网个特殊需求时总结而来,需要的朋友可以参考下
在编写PHP模板引擎工具类时,以前常用的一个正则替换函数为 preg_replace(),加上正则修饰符 /e,就能够执行强大的回调函数,实现模板引擎编译(其实就是字符串替换)。
详情介绍参考博文:PHP函数preg_replace() 正则替换所有符合条件的字符串
应用举例如下:
代码如下:
<?php
/**
* 模板解析类
*/
class Template {
/**
* 模板解析类
*/
class Template {
public function compile($template) {
// if逻辑
$template = preg_replace(“/\/e”, “\$this->ifTag(‘\\1’)”, $template);
return $template;
}
/**
* if 标签
*/
protected function ifTag($str) {
//$str = stripslashes($str); // 去反转义
return ”;
}
}
$template = ‘xxxyyyzzz’;
$tplComplier = new Template();
$template = $tplComplier->compile($template);
echo $template;
?>
以上就是PHP正则替换函数preg_replace和preg_replace_callback使用总结的详细内容,更多请关注gaodaima搞代码网其它相关文章!