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

jolyonruss
  • 1,770
  • 2
  • 19
  • 34
kironet
  • 766
  • 2
  • 11
  • 27
  • 3
    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. – Syscall Mar 18 '18 at 13:07

1 Answers1

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);
HPierce
  • 7,249
  • 7
  • 33
  • 49
  • "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. – salathe Mar 18 '18 at 13:34
  • @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). – HPierce Mar 18 '18 at 13:43
  • 2
    The `(?<=...)` is a [lookbehind assertion](https://www.regular-expressions.info/lookaround.html), not a [capturing group](https://www.regular-expressions.info/brackets.html). – salathe Mar 18 '18 at 18:44