PHP7 - The /e modifier is no longer supported, use preg_replace_callback instead [duplicate]
Asked Answered
V

1

8

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

Votaw answered 18/3, 2018 at 13:3 Comment(1)
Your e modifier has no more sense in your preg_replace_callback() code. Remove it. Then a return in foreach will stop the loop at the first iteration.Attaint
J
14

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);
Jacksmelt answered 18/3, 2018 at 13:26 Comment(3)
"The match will always be in the second item in the array." – it is the first (and only) array item, in the OP's case, since they're not using capturing groups.Darby
@salathe, I don't follow. I see a pair of () in the OP? None of the code provided in the OP would make sense without a capture group (which is totally there).Jacksmelt
The (?<=...) is a lookbehind assertion, not a capturing group.Darby

© 2022 - 2024 — McMap. All rights reserved.