简体   繁体   中英

php single and double quotes

//remove line breaks
function safeEmail($string) {
     return  preg_replace( '((?:\n|\r|\t|%0A|%0D|%08|%09)+)i' , '', $string );
}

/*** example usage 1***/
$from = 'HTML Email\r\t\n';

/*** example usage 2***/
$from = "HTML Email\r\t\n";

if(strlen($from) < 100)
{
    $from = safeEmail($from);

    echo $from;
}

1 returns HTML Email\\r\\t\\n while 2 returns HTML Email

what's with the quotes?

As per the PHP Documentation

Unlike the double-quoted and heredoc syntaxes, variables and escape sequences for special characters will not be expanded when they occur in single quoted strings.

In other words, double quoted strings expand variables and escape sequences for special characters. Single quoted strings don't.

So in example1, with the single quoted string, the string is exactly as you see it. Slashes and all.

But in example2, rather than ending with the string \\r\\t\\n , it ends with a carriage return, a tab and then a new line. In other words the escape sequences for special characters are expanded.

with single quotes in PHP those special characters as \\n \\r \\t... doesn't work as expected. According to the docs :

To specify a literal single quote, escape it with a backslash ( \\ ). To specify a literal backslash, double it ( \\\\ ). All other instances of backslash will be treated as a literal backslash: this means that the other escape sequences you might be used to, such as \\r or \\n , will be output literally as specified rather than having any special meaning.

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