问题
I want to remove all \r
\n
\r\n
which is pretty easy to so I wrote:
str_replace(array("\r","\n"),"",$text);
but I saw this line:
str_replace(array("\r","\n","\\r","\\n"),"",$text);
and I was wondering what is the double backslash means \\r
and \\n
.
回答1:
\
is an escape character, it's used to escape the following character.
In "\n"
, the backslash escapes n
and the result will be a new line character.
In "\\n"
, the first backslash escapes the second backslash and the n
is kept as is, so the result is a string containing \n
(literally).
See the PHP official documentation > Strings.
In the context of your question, str_replace()
will remove new lines ("\n"
and "\r"
) and also remove \n
and \r
from the string ("\\n"
and "\\r"
respectively). There's no reason a text contains the words \n
and \r
, so it seems that using "\\n"
and "\\r"
has no interest here.
回答2:
The first backslash escapes the second one, so it matches a literal backslash in $text
.
I'm not sure why you would want to match that if you just want to remove newlines and carriage returns from the string.
来源:https://stackoverflow.com/questions/27290840/in-phps-str-replace-what-does-the-double-backslash-mean