0

I have a problem with the function preg_replace_callback() in PHP. I want to call a function which requires two parameters.

private function parse_variable_array($a, $b)
{
    return $a * $b;
}

On the internet I found this piece of code:

preg_replace_callback("/regexcode/", call_user_func_array(array($this, "foo"), array($foo, $bar)), $subject);

But in the function foo I cannot use the matches array that is usual with a preg_replace_callback

I hope you can help me!

The Nail
  • 8,355
  • 2
  • 35
  • 48
Remy Strijker
  • 261
  • 3
  • 19

1 Answers1

5

The callback is called as is, you cannot pass additional parameters to it. You can make a simple wrapper function though. For PHP 5.3+, that's easily done with anonymous functions:

preg_replace_callback(..., function ($match) {
    return parse_variable_array($match, 42);
}, ...);

For older PHP versions, make a regular function that you pass as usual as the callback.

deceze
  • 510,633
  • 85
  • 743
  • 889
  • 2
    You can also declare additional parameters for an anonymous function: `function ($matches) use ($otherVar) { ... }` which might help (as well as avoiding `global`). – cmbuckley Jan 05 '12 at 00:30
  • Pedantically that's not "declaring additional parameters", it's clojuring up some context. :) – deceze Jan 05 '12 at 00:39
  • The problem is I have to work with PHP version 5.2.17. The '42' in your example needs to be a parameter of a function, so I can't refer to a local variable or something. You said i should make a reglar function, but I don't see the possibilities. Can you help me again? – Remy Strijker Jan 05 '12 at 01:36
  • @Remy `function myCallback ($match) { ... }` Then: `preg_replace_callback(..., 'myCallback', ...)`. It's the same thing with different semantics. I don't know what you mean by your explanation about `42`. Where's that value supposed to come from exactly? – deceze Jan 05 '12 at 02:03
  • @deceze The funnction 'parse_variable_repalce' (shown below), is also called with an preg_replace_callback. Here is some bigger example. `private function parse_variable_replace($find_var_name, $replacement, $subject) { $return .= preg_replace_callback("/\{\\\$([^\ {]*)\}/is", $this->test($matches, $find_var_name, $replacement), $subject); return $return; }` – Remy Strijker Jan 05 '12 at 02:06
  • @Remy It's very difficult to pass such state along into callback functions. If you can't use anonymous functions with closures, your only hope really is to save these extra parameters as properties of your `$this` object which your callback function can use. Also, `$this->test(...)` executes the `test` function right there, if you want to pass it as callback, you'll have to use `array($this, 'test')` instead. If you want a more complete example, please post your code into your question to make it better comprehensible. – deceze Jan 05 '12 at 02:37