stuck with Preg_replace() to Preg_replace_callback()

89 Views Asked by At

I am trying to convert this function to preg_replace_callback but almost everything that I tried gives error:

Requires argument 2, '$db->module', to be a valid callback in

This is my code:

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

Any ideas how to convert it?..

1

There are 1 best solutions below

0
On

I answer this question exceptionally because you have to use a class method in it. So it isn't so simple than the million of answers about the subject.

One way to do it, change the pattern in a way the whole match is the yourclass::module parameter and pass an array with $this and the method name as second parameter:

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

or

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

Other way, keep the same pattern and use the $that=$this; trick:

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