如何将以下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 :(得分:2)
不要在preg_replace_callback()调用中使用\ e修饰符,否则php将抛出以下警告并且不返回任何内容:
PHP警告:preg_replace_callback():修饰符/ e不能用于 在xx
的/wherever/you/used/it.php中替换回调
另外,只是一个建议,不要在回调函数中使用$ this作为参数名称......这只是令人困惑。
答案 1 :(得分:2)
为了正确使用' $ this'在上下文中,您需要为匿名函数提供use关键字。此外,$ this是一个特殊变量,它的不良做法是直接将其用作函数参数。同样在您的匿名函数中,您尝试使用$ 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 );
答案 2 :(得分:0)
因为您缺少分号 ;
return $this->check_group($this[1], $this[2], false);
-------^ // Here