-1

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?..

Dikobraz
  • 649
  • 2
  • 8
  • 22
  • a callback is a function, which parameters and return values should be carefully chosen with respect to http://php.net/manual/en/function.preg-replace-callback.php – Calimero Sep 19 '17 at 09:49
  • I will reopen the question since it is a particular case in which a class method needs to be used the callback function. – Casimir et Hippolyte Sep 19 '17 at 09:56

1 Answers1

3

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);
IMSoP
  • 89,526
  • 13
  • 117
  • 169
Casimir et Hippolyte
  • 88,009
  • 5
  • 94
  • 125