2014-01-06 47 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); 
相關問題