PHP正则替换函数preg_replace和preg_replace_callback使用总结(2)
<?php
// 将文本中的年份增加一年.
$text = "April fools day is 04/01/2002\n";
$text.= "Last christmas was 12/24/2001\n";
// 回调函数
function next_year($matches) {
// 通常: $matches[0]是完成的匹配
// $matches[1]是第一个捕获子组的匹配
// 以此类推
return $matches[1].($matches[2]+1);
}
echo preg_replace_callback(
"|(\d{2}/\d{2}/)(\d{4})|",
"next_year",
$text);
?>
Example #3 preg_replace_callback() 和 类方法
如何在类的内部调用非静态函数?你可以按如下操作:
对于 PHP 5.2,第二个参数 像这样 array($this, 'replace') :
<?php
class test_preg_callback{
private function process($text){
$reg = "/\{([0-9a-zA-Z\- ]+)\:([0-9a-zA-Z\- ]+):?\}/";
return preg_replace_callback($reg, array($this, 'replace'), $text);
}
private function replace($matches){
if (method_exists($this, $matches[1])){
return @$this->$matches[1]($matches[2]);
}
}
}
?>
对于 PHP5.3,第二个参数像这样 "self::replace" :
注意,也可以是 array($this, 'replace')。
<?php
class test_preg_callback{
private function process($text){
$reg = "/\{([0-9a-zA-Z\- ]+)\:([0-9a-zA-Z\- ]+):?\}/";
return preg_replace_callback($reg, "self::replace", $text);
}
private function replace($matches){
if (method_exists($this, $matches[1])){
return @$this->$matches[1]($matches[2]);
}
}
}
?>
根据上面所学到的知识点,把模板引擎类改造如下:
<?php
/**
* 模板解析类
*/
class Template {
public function compile($template) {
// if逻辑
$template = preg_replace_callback("/\<\!\-\-\{if\s+(.+?)\}\-\-\>/", array($this, 'ifTag'), $template);
return $template;
}
/**
* if 标签
*/
protected function ifTag($matches) {
return '<?php if (' . $matches[1] . ') { ?>';
}
}
$template = 'xxx<!--{if $user[\'userName\']}-->yyy<!--{if $user["password"]}-->zzz';
$tplComplier = new Template();
$template = $tplComplier->compile($template);
echo $template;
?>
输出结果为:
xxx<?php if ($user['userName']) { ?>yyy<?php if ($user["password"]) { ?>zzz
正是我们想要的结果,双引号没有被反转义!
- 上一篇:11个PHPer必须要了解的编程规范
- 下一篇:php分页函数完整实例代码