In PHP's str_replace(), what does the double backslash mean?

╄→尐↘猪︶ㄣ 提交于 2021-02-05 05:41:12

问题


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

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!