2014-01-06 91 views
2

如何将以下preg_replace转换为preg_replace_callback?已弃用:preg_replace():如何转换为preg_replace_callback?

  $this->template = preg_replace ("#\\[group=(.+?)\\](.*?)\\[/group\\]#ies", 
"\$this->check_group('\\1', '\\2')", $this->template); 

我已经试过:

 $this->template = preg_replace_callback("#\\[not-group=(.+?)\\](.*?)\\[/not-group\\]#ies", 
       function($this) { 
         return $this->check_group($this[1], $this[2], false); 
       } 
     , $this->template); 

和上述preg_replace_callback给我一个空的结果。

回答

0

因为你缺少一个分号;

return $this->check_group($this[1], $this[2], false); 
              -------^ // Here 
+0

您是否可以在问题中更新测试数据和预期输出? –

+0

它似乎在php5.5中不能使用e修饰符。将'#ies'改为'#isu',现在它正在工作 – Orlo

2

不要在preg_replace_callback使用\ e修饰符()调用或PHP会抛出以下警告,并返回任何结果:

PHP Warning:preg_replace_callback():修饰符/ e不能与 替换回调一起使用/wherever/you/used/it.php在线xx

此外,只是一个建议,不要使用$ this作为您的回调函数中的参数名称......这只是令人困惑。

2

为了在上下文中正确使用'$ this',您需要为匿名函数提供use关键字。此外,$这是一个特殊的变量,它的直接用作函数参数的做法很糟糕。同样在你的匿名函数中,你试图用$ this作为你的匹配变量,并且我会用函数参数中的$ this替换一个更具描述性的变量'$ matches'。看看下面是否解决你的问题。

$this->template = preg_replace_callback("#\\[not-group=(.+?)\\](.*?)\\[/not-group\\]#is", 
      function($match) use ($this) { 
        return $this->check_group($match[1], $match[2], false); 
      } 
    , $this->template); 
相关问题