Search code examples
phpparameterspreg-replace-callback

Second parameter in preg_replace_callback()


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!


Solution

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