1

I am currently re-programming a framework in php and I upgraded our development server to php 5.5.3. When I fire up the webbrowser, it returns the following error:

[19-Oct-2013 16:54:05 Europe/Amsterdam] PHP Deprecated:  preg_replace(): The /e modifier is deprecated, use preg_replace_callback instead in /Applications/MAMP/htdocs/fw/lib/lang.php on line 57

And line 57 is;

$response = preg_replace('/\{'.$find.'(:(.*))?\}/Ue', 'str_replace("{value}", "\\2", $replace)', $response);

I am really horrible at reading these php documentation, I am a beginner and simply changing preg_replace() by preg_replace_callback() is too good to be true. A co-worker told me it had to be something like $value[1] but that didn't work eather.

Is there a simple solution, am I overlooking something?

Patrick Kostjens
  • 5,065
  • 6
  • 29
  • 46

1 Answers1

3

Here is the page about modifiers, giving you more detail about why it is deprecated, and what that means exactly.

Basically the reason is that the /e modifier causes a string to be evaluated as PHP code, as if eval was called. Using preg_replace_callback instead, which allows you to pass it an actual PHP function is indeed the way to go.

If you replace the string-code (second parameter) by an anonymous function, your code should then look something like this:

$response = preg_replace_callback(
    '/\{'.$find.'(:(.*))?\}/U', 
    function($m) use ($replace) {
      return str_replace($m, "\\2", $replace);
    } , 
    $response);

The keyword use makes sure that the anonymous function can use the $replace variable which should be defined in the calling scope. See this discussion.

Community
  • 1
  • 1
GolezTrol
  • 114,394
  • 18
  • 182
  • 210
  • Note that you can also send [`preg_replace_callback`](http://php.net/preg_replace_callback) an [anonymous function](http://php.net/manual/en/functions.anonymous.php), as shown in the linked articles. – Marcel Korpel Oct 19 '13 at 15:10
  • 1
    I never heard about the [`use` keyword](http://blog.dubbelboer.com/2012/04/07/php-use-keyword.html). Every day is a learning day! – Marcel Korpel Oct 19 '13 at 15:20
  • Thank you everybody for your reactions. After I changed the string-code by an anonymous function, I get the following error: `PHP Catchable fatal error: Object of class Closure could not be converted to string`. I think I need to implement the _callback function. Oh and did I forgot to mention that this code is inside a `foreach($key as $find=>$replace)` loop? Maybe this error has to do something with that? I am not sure. –  Oct 19 '13 at 18:13
  • 1
    My bad. I forgot to actually use `preg_replace_callback`. I still called `preg_replace` in my answer, causing PHP to try to convert the function to a string. I assume you copied that and also overlooked my mistake. I've updated the code example. – GolezTrol Oct 19 '13 at 22:31