PHP7 - The /e modifier is no longer supported, use preg_replace_callback instead

kironet picture kironet · Mar 18, 2018 · Viewed 24.9k times · Source

Can somebody help me with this error I'm getting?

Warning: preg_replace(): The /e modifier is no longer supported, use preg_replace_callback instead

My original code:

$match[1] = preg_replace('/(?<=^|[\x09\x20\x2D])./e', 'strtoupper("\0")', strtolower(trim($match[1])));

So I tried it like this:

$match[1] = preg_replace_callback('/(?<=^|[\x09\x20\x2D])./e',
                    function ($matches) {
                        foreach ($matches as $match) {
                            return strtoupper($match);
                        }
                    },
                    strtolower(trim($match[1])));

But I'm still getting the same error:

Warning: preg_replace_callback(): The /e modifier is no longer supported, use preg_replace_callback instead

Answer

HPierce picture HPierce · Mar 18, 2018

The error message is telling you to remove the e modifier that you've included in your new code.

/ (?<=^|[\x09\x20\x2D]). / e
^ ^------Pattern-------^ ^ ^ ---- Modifiers
|                        |
 -------Delimiters-------

You need to remove the modifier, so preg_replace_callback('/(?<=^|[\x09\x20\x2D])./e', ...) should be preg_replace_callback('/(?<=^|[\x09\x20\x2D])./' , ...).

As an aside, you aren't benefiting from using a foreach loop in your new code. The match will always be in the second item in the array. Here's an example without using a loop:

$inputString = 'foobazbar';

$result = preg_replace_callback('/^foo(.*)bar$/', function ($matches) {
     // $matches[0]: "foobazbar" 
     // $matches[1]: "baz" 
     return "foo" . strtoupper($matches[1]) . "bar";
}, $inputString);

// "fooBAZbar"
var_dump($result);