简体   繁体   English

php单引号和双引号

[英]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 1返回HTML Email \\ r \\ t \\ n,而2返回HTML Email

what's with the quotes? 什么是报价?

As per the PHP Documentation 根据PHP文档

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. 与双引号和heredoc语法不同,特殊字符的变量和转义序列在单引号字符串中出现时不会被扩展。

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. 所以在example1中,使用单引号字符串,字符串就像你看到的那样。 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. 但是在example2中,它不是以字符串\\r\\t\\n结尾,而是以回车符,选项卡和新行结束。 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. 在PHP中用单引号表示\\ n \\ r \\ t \\ ...的特殊字符不能按预期工作。 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. 反斜杠的所有其他实例将被视为文字反斜杠:这意味着您可能习惯使用的其他转义序列(如\\r\\n )将按字母顺序输出,而不是具有任何特殊含义。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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