1

Why does the 2nd case not make the replacement? Isn't '}' a non-word character? Including the forward slash is necessary in the original code that I was working on.

// Works
$s = 'abc/stringToReplace-ABC';
$pattern = '/\b\/stringToReplace\b/';
$s2 = preg_replace($pattern, '/-replacement', $s);
echo $s2 . PHP_EOL;     // output: abc/-replacement-ABC

// Doesn't work.
$s = 'abc}/stringToReplace-ABC';
$pattern = '/\b\/stringToReplace\b/';
$s2 = preg_replace($pattern, '/-replacement', $s);
echo $s2 . PHP_EOL;     // output: abc}/stringToReplace-ABC
user3341576
  • 181
  • 1
  • 2
  • 16
  • 1
    `\b` is only matched before or after a word character whereas `}` and `/` are both non-word characters. There is no need to use `\b` just before `/` in your regex. – anubhava Jun 24 '20 at 19:09
  • `}` is a non-word char, but `\b` - before a non-word char like `/` - requires a word char before it. Use unambiguous word boundaries, `(?<!\w)...(?!\w)`, or whitespace ones, `(?<!\S)...(?!\S)` – Wiktor Stribiżew Jun 24 '20 at 20:00

0 Answers0