Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

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.

like image 292
Steven Avatar asked Feb 11 '23 10:02

Steven


1 Answers

\ 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.

like image 117
A.L Avatar answered Feb 13 '23 23:02

A.L