48
$result = preg_replace(
    "/\{([<>])([a-zA-Z0-9_]*)(\?{0,1})([a-zA-Z0-9_]*)\}(.*)\{\\1\/\\2\}/iseU", 
    "CallFunction('\\1','\\2','\\3','\\4','\\5')",
    $result
);

The above code gives a deprecation warning after upgrading to PHP 5.5:

Deprecated: preg_replace(): The /e modifier is deprecated, use preg_replace_callback instead

How can I replace the code with preg_replace_callback()?

tereško
  • 58,060
  • 25
  • 98
  • 150
dima.h
  • 860
  • 2
  • 10
  • 14

1 Answers1

70

You can use an anonymous function to pass the matches to your function:

$result = preg_replace_callback(
    "/\{([<>])([a-zA-Z0-9_]*)(\?{0,1})([a-zA-Z0-9_]*)\}(.*)\{\\1\/\\2\}/isU",
    function($m) { return CallFunction($m[1], $m[2], $m[3], $m[4], $m[5]); },
    $result
);

Apart from being faster, this will also properly handle double quotes in your string. Your current code using /e would convert a double quote " into \".

NikiC
  • 100,734
  • 37
  • 191
  • 225
  • 1
    `[a-zA-Z0-9_]` should be shortened to `\w`, `{0,1}` to `?`, and the `i` pattern modifier serves to useful purpose. – mickmackusa Feb 05 '21 at 19:53