龙盟编程博客 | 无障碍搜索 | 云盘搜索神器
快速搜索
主页 > web编程 > php编程 >

PHP正则替换函数preg_replace和preg_replace_callback使用总结(2)

时间:2014-09-23 11:00来源:网络整理 作者:网络 点击:
分享到:
复制代码 代码如下: php // 将文本中的年份增加一年. $text = "April fools day is 04/01/2002\n"; $text.= "Last christmas was 12/24/2001\n"; // 回调函数 function next_year($matches)

复制代码 代码如下:

<?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

正是我们想要的结果,双引号没有被反转义!

精彩图集

赞助商链接