Why is '\ n' === '\\ n' true in php?

I understand that:

'\n' // literally the backslash character followed by the character for lowercase n "\n" // interpreted by php as the newline character 

But for life, I can’t understand why '\n' === '\\n' . In my opinion, '\\n' will be equal to three separate characters: two separate backslashes followed by the letter n.

Why does '\n' === '\\n' true exist in PHP?

+4
source share
3 answers

The backslash is still an escape character in single-quoted strings (it comes out of single literal quotes).

This is illegal, for example (since the backslash avoids the closing quote):

 $path = 'C:\'; 

So, \\ must match a literal backslash to avoid inadvertent escaping.

+4
source

From the manual section ( about single quotes ):

To specify a single letter quotation mark, follow its backslash ( \ ). To specify a literal backslash, double it ( \\ ). All other backslash instances will be treated as a literal backslash.

therefore, in a single quoted string \n there are two characters, but \\n is a literal backslash followed by the letter "n", that is, the same two characters.

+10
source

This is because '\\n' is actually \n , because the backslash is an escape character that acts strangely in single quotes. It does not run away n , but exits \

+2
source

All Articles