"use preg_replace_callback instead" error on PHP 7

Post Reply
User avatar
Edge100x
Founder
Founder
Posts: 13015
https://www.youtube.com/channel/UC40BgXanDqOYoVCYFDSTfHA
Joined: Thu Apr 18, 2002 11:04 pm
Location: Seattle
Contact:

"use preg_replace_callback instead" error on PHP 7

Post by Edge100x »

If you're receiving an error like this:

Code: Select all

Warning: preg_replace(): The /e modifier is no longer supported, use preg_replace_callback instead in /usr/www/identifier/public/script.php on line 977
.. it means that your software uses an old mechanism that PHP 7 removed. You should be able to edit your code to fix it with these steps.
  1. Download the script through SFTP and open it in your favorite text editor (or, edit it directly on the webserver using SSH and a text editor there).
  2. Go to the line number specified by the error.
  3. Look for use of the preg_replace() function on this line. The first argument to the function will end in an "e"., the second argument will be after a comma and contain arbitrary code, and the third argument should be a variable. For instance:

    Code: Select all

    $source = preg_replace('/&#(\d+);/me', "utf8_encode(chr(\\1))", $source);
  4. Edit the function call in the following ways.
    1. Change the function name from preg_replace to preg_replace_callback.
    2. Remove the "e" at the end of the first argument.
    3. Replace the text of the second argument with an anonymous function in a form like this:

      Code: Select all

      function($m) {  return something; }
      
      Replace the "something" with the current value of the second argument.
    4. Remove the quotation marks around the second argument.
    5. Remove escapes (backslashes) for regular names in the second argument, since they are no longer inside a string -- changing \$ to $, for instance. (If the argument is complicated, you may need to perform other changes to convert it to directly executable PHP code.)
    6. Change all of the references in the second argument -- which look like \\x, where "x" is a number -- to the form $m[x].
  5. Re-upload, or save, your script.
  6. Wait a few seconds, then load your page again to confirm that the error went away.

At the end, in the file, you should have something like this:

Code: Select all

$source = preg_replace_callback('/&#(\d+);/m', function($m) {  return utf8_encode(chr($m[1])); } , $source);

To make it prettier, you could put it on multiple lines:

Code: Select all

$source = preg_replace_callback(
  '/&#(\d+);/m', 
  function($m) {  return utf8_encode(chr($m[1])); } , 
  $source
);
Post Reply