Question

I attempted the following code:

$for_callback=create_function('$match','return $GLOBALS[\'replacements\'][$match[1]];');
$result = preg_replace_callback( $regex, '$for_callback', $string);

The variable $GLOBALS['replacements'] is generated dynamically before this function is called.

I get an error message like

Warning: preg_replace_callback() [function.preg-replace-callback]: Requires argument 2, '$for_callback', to be a valid callback in...

created functions and callbacks are both new to me. This is growing out of some code given to me by nickb at My question about preg_replace that turned into preg_replace_callback.

What I'm trying to do is wrap the code in that answer into a function and I'm running into errors with scope avoiding re-defining a function. (upgrading to PHP 5.3+ is a remote posibility option for me at the moment.)

How do I get this to work?

Was it helpful?

Solution

First, variables must not be enclosed with single quotes, as they will not be replaced with the real value.

And second, you should use anonymous functions (i.e. closures) instead as they are much easier. Use them like in this example:

$for_callback = function($match) {
    return $GLOBALS['replacements'][$match[1]];
};
$result = preg_replace_callback( $regex, $for_callback, $string);

edit: Closures became available in PHP 5.3. So if you are still using PHP < 5.3 you should (really update or) use the following:

$for_callback=create_function('$match','return $GLOBALS[\'replacements\'][$match[1]];');
$result = preg_replace_callback( $regex, $for_callback, $string);
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top