1

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?

1 Answer 1

4

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.

Sign up to request clarification or add additional context in comments.

1 Comment

+1. It gets really confusing when you realise that even some characters that would be picked up by PHP as escape sequences don't need to be double-escaped because the escaped character is valid inside the regex. So you can get away with \n, or you can escape it \\n. But where it really gets bad is when you have an actual backslash in your string to search for. Try matching a Windows network path (`\\nas\folder\etc`) or a find escaped characters in a JSON string, and you'll end up with a monstrous cascade of backslashes. Fun fun fun.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.