views:

99

answers:

2

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.

A: 

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,

MattSmith
+1  A: 

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);
chris
I was looking at that, but our system runs on 5.2.6 :(.
Steven Xu