当前位置: 动力学知识库 > 问答 > 编程问答 >

php - Codeigniter preg_replace_callback

问题描述:

I would like for preg_replace_callback to use a library function from CodeIgniter as its callback. My current unsuccessful attempt is the following:

$content = preg_replace_callback('/href="(\S+)"/i',

'$this->util->url_to_absolute("http://www.google.com","$matches[0]")',

$content);

But I haven't had any success. I've tried using create_function, but I can't get that to work either. Any help would be greatly appreciated.

网友答案:

As of 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);
网友答案:

It would look something more like:

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

But the issue is that the $this reference won't be available inside callback scope so you may need to instantiate it inside the callback or use a callback into your own class e.g.:

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;
    }
}

Assuming class fred and dostuff is the class and method where you are trying to call this from at the moment,

分享给朋友:
您可能感兴趣的文章:
随机阅读: