Wednesday, April 29, 2015

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

Recently tried upgrading PHP version from 5.2 to 5.5 and one of our package program ECSHOP thrown bunches of errors and warning. Yes, our company's shared hosting PHP version is seriously outdated, still mainly using PHP5.2, due to the lack-of-update ECSHOP program ... (yes we still have huge number of ECSHOP clients with us).

First thing I saw ECSHOP running on PHP5.5 is the following warning message :

Deprecated: preg_replace(): The /e modifier is deprecated, use
preg_replace_callback instead in /home/name/domains/domain.com/
public_html/includes/cls_template.php on line 300


Immediately went Google to run a brief search, find out that it is the /e is causing the warning. And to resolve it, had to change to use preg_replace_callback function instead.

Opening the script, found the problem script as :

return preg_replace("/{([^\}\{\n]*)}/e", "\$this->select('\\1');", $source);

And change it to :
return preg_replace_callback('/{([^\}\{\n]*)}/', 
    function($matches) {
       return $this->select($matches[1]);
    }, $source);

This issue affects all preg_ functions, and it's not too difficult to migrate actually.
  1. Change the function to preg_ function to preg_<func>_callback.
  2. The first parameter (regex expression) remain the same, only remove the e identifier from the regex.
  3. Second parameter changed to use function($matches) {}, then inside the function will be what originally used in the old deprecated function (remove the quotes!).
  4. Inside the function, find all respective arguments (i.e. \\1, \\2), and replace them in the new function with $matches[<index>]. The <index> would be follow what were used originally (i.e. \\1, \\2).
  5. Third parameter just remain the same.


Please be aware to to use $this directly inside the created function, your PHP version must be version 5.5 and above.

No comments:

Post a Comment