0

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?

Community
  • 1
  • 1
TecBrat
  • 3,643
  • 3
  • 28
  • 45
  • `'$match'` should be just `$match`, or if you're in a cargo cult programming mood, `"$match"`. ditto for the other quoted variables. – Marc B Jul 11 '13 at 16:04
  • I thought that looked odd, but here's a clip from php.net: $newfunc = create_function('$a,$b', 'return "ln($a) + ln($b) = " . log($a * $b);');. It looks like PHP evals that code. The actual error was not in my `create_fuction()` but in my `preg_replace_callback()` where I left single quotes around the function variable where they didn't belong. – TecBrat Jul 11 '13 at 18:01

1 Answers1

1

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);
str
  • 42,689
  • 17
  • 109
  • 127
  • My version of PHP does not support the closure, but apparently does support the `create_function()` – TecBrat Jul 11 '13 at 16:08
  • Just reflected that in my answer. However, you should *really, really* update your PHP version. – str Jul 11 '13 at 16:09
  • Ever have one of those moments where you can't find the tree you're looking for in the middle of the forest? I mis-read your answer and didn't see that you corrected my `, '$for_callback',`. Those quotes were left over from where I tried a named function. – TecBrat Jul 11 '13 at 17:43