简体   繁体   中英

Why PHP does not escape single quote string but reserve the forward slash?

Are there any reason why forward slash need to be printed via \\\\ even with single quoted string?

eg

php -r "print '\n';" # echo \n

Since single quotea string does not handle escape characters, so why the following statement is not valid?

php -r "print '\n\';"

Parse error: parse error in Command line code on line 1

Well, no variable substitution and no escaping is done for strings in single-quotes with the exception for escaped single quotes within a single quoted string to allow you to insert a single quote into your string without having to use a double-quoted string for that special case.

Therefore your example will properly escape the string-terminating single quote, resulting in an unterminated string, causing the parse error.

So to print a backslash in front of a single quote within a single-quoted string, you'll have to escape the backslash itself. The single quote and the backslash in front of a single quote are the only characters you have to escape within a single-quoted string. All other characters will not get their special meaning applied if you use an escape sequence.

For single quotes, \\' represents a literal single quote. Thus, your string is never closed.

If you have a web server installed on your computer the script you want to run is `

echo "\\n";

?>`

in order to print a newline character

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM