Codeigniter preg_replace_callback

时间:2010-02-11 01:26:33

标签: php codeigniter callback

我希望preg_replace_callback使用CodeIgniter中的库函数作为其回调。我目前的失败尝试如下:

$content = preg_replace_callback('/href="(\S+)"/i',
    '$this->util->url_to_absolute("http://www.google.com","$matches[0]")',
    $content);

但我没有取得任何成功。我尝试过使用create_function,但我也无法使用它。任何帮助将不胜感激。

2 个答案:

答案 0 :(得分:1)

看起来更像是:

$content = preg_replace_callback(
    '/href="(\S+)"/i',
    create_function(
        '$matches',
        'return $this->util->url_to_absolute("http://www.google.com","$matches[1]")'),
    $content);

但问题是$ this引用在回调范围内不可用,因此您可能需要在回调中实例化它或使用回调到您自己的类中,例如:

class fred {

    function callback1($matches) {
       return $this->util->url_to_absolute("http://www.google.com","$matches[1]");
    }

    function dostuff($content) {
        $content = preg_replace_callback(
            '/href="(\S+)"/i',
            array($this, 'callback1'),
            $content);
        return $content;
    }
}

假设类fred和dostuff是您尝试从此处调用此类的类和方法,

答案 1 :(得分:1)

从php 5.3开始

$that = $this;
$content = preg_replace_callback($patt, function($matches) use ($that) {
    return $that->util->url_to_absolute("http://www.google.com", $matches[1]);
}, $content);

//or
$that = $this->util;
$content = preg_replace_callback($patt, function($matches) use ($that) {
    return $that->url_to_absolute("http://www.google.com", $matches[1]);
}, $content);

//or
$callback = array($this->util, 'url_to_absolute');
$content = preg_replace_callback($patt, function($matches) use ($callback) {
    return call_user_func($callback, "http://www.google.com", $matches[1]);
}, $content);