This might be a dumb question, but I have trouble understanding why the following code works as expected
$text = "ab cd";
$text = preg_replace("/\s+/", "", $text);
echo $text;
and outputs abcd
.
Shouldn't the backslash in \s
be escaped to get its literal meaning inside the regular expression?
Not necessarily, because the string literal rules say that if \
is followed by anything other than another \
or a '
it is treated as any other character. This general rule also affects double-quoted strings, although in that case there are more recognized escape sequences than just these two.
You could escape it if you wanted to, but personally I think the world has enough backslashes already.