【问题标题】:stuck with Preg_replace() to Preg_replace_callback()坚持 Preg_replace() 到 Preg_replace_callback()
【发布时间】:2017-09-19 09:47:51
【问题描述】:

我正在尝试将此函数转换为 preg_replace_callback 但我尝试的几乎所有操作都会出错:

需要参数 2“$db->module”作为有效回调

这是我的代码:

$this->template = preg_replace ("/#module\=(\w+)#/ie", "\$this->module('\\1')", $this->template);

任何想法如何转换它?..

【问题讨论】:

标签: php preg-replace preg-replace-callback


【解决方案1】:

我特别回答这个问题,因为你必须在其中使用一个类方法。所以它并不比关于这个主题的数百万个答案那么简单。

一种方法是改变模式,整个匹配是yourclass::module参数,并传递一个带有$this的数组和方法名称作为第二个参数:

$this->template = preg_replace_callback('/#module=\K\w+(?=#)/i', array($this, 'module'), $this->template);

$this->template = preg_replace_callback('/#module=\K\w+(?=#)/i', 'self::module', $this->template);

否则,保持相同的模式并使用$that=$this; 技巧:

$that = $this;
$this->template = preg_replace_callback('/#module=(\w+)#/i', function ($m) use ($that) {
    return $that->module($m[1]);
}, $this->template);

【讨论】:

    猜你喜欢
    • 2017-06-02
    • 2014-04-27
    • 2016-02-07
    • 1970-01-01
    • 2015-08-09
    • 2011-12-10
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多