Just Jacob Just Jacob - 9 months ago 68
HTML Question

What happens when you escape numbers?

I have this code that replaces match of a regex capture group with a back-reference, but the matched text was always replaced with nothing i.e. cut of.

The code.

$str = 'string is string';
$replacement_result = preg_replace("/(\w+) is (\w+)/","\1 this \2", $str);

echo $replacement_result;
// results was 'is'

I then noticed that the replacement parameter string was in double quote and was escaping the number(which i thought would work fine), so I changed the double quotes to single quotes

$str = 'string is string';
// changes here
$replacement_result = preg_replace("/(\w+) is (\w+)/",'\1 this \2', $str);

echo $replacement_result;
// results was 'string this string'

I even tried document.write()ing and escaped number in Javascript and 'twas the same result (nothing).

So obviously this is my first encounter with this, and there is a very simple 1 - 2 line answer.
What happens when a number is escaped?

Answer Source

According to the official documentation, within a double-quoted string, a backslash followed by a sequence of 1..3 digits between 0 and 7 is interpreted as a character in octal notation:

\[0-7]{1,3} the sequence of characters matching the regular expression is a character in octal notation, which silently overflows to fit in a byte (e.g. "\400" === "\000")