简述
Php中字符串有四种方式定义,分别是单引号、双引号、Heredoc以及Nowdoc,常使用的是前两种,使用单引号将以纯字符串的方式处理数据(可以使用\转义'),双引号会对一些特殊字符进行解析,而后两者则是对长文本的存储方式。
示例
- 单引号
<?php
echo 'this is a simple string';
// 可以录入多行
echo 'You can also have embedded newlines in
strings this way as it is
okay to do';
// 输出: Arnold once said: "I'll be back"
echo 'Arnold once said: "I\'ll be back"';
// 输出: You deleted C:\*.*?
echo 'You deleted C:\\*.*?';
// 输出: You deleted C:\*.*?
echo 'You deleted C:\*.*?';
// 输出: This will not expand: \n a newline
echo 'This will not expand: \n a newline';
// 输出: Variables do not $expand $either
echo 'Variables do not $expand $either';
?>
- 双引号
如果字符串是包围在双引号(")中, PHP 将对一些特殊的字符进行解析:
<?php
$a = 12;
// 输出:I have 12 apples
echo "I have $a apples";
echo "\n";
// 输出:I think I can complete it in 12s
echo "I think I can complete it in {$a}s";
所以如果需要在字符串中插入换行要使用双引号
- Heredoc
Heredoc是以<<<开头,在该运算符之后要提供一个标识符,然后换行。接下来是字符串 string 本身,最后要用前面定义的标识符作为结束标志。
结束时所引用的标识符必须在该行的第一列,而且,标识符的命名也要像其它标签一样遵守 PHP 的规则:只能包含字母、数字和下划线,并且必须以字母和下划线作为开头。
$name = 'Yukino';
echo <<<EOT
My name is "$name".
This should print a capital 'A': \x41
EOT;
输出:
My name is "Yukino".
This should print a capital 'A': A
- Newdoc
就象 heredoc 结构类似于双引号字符串,Nowdoc 结构是类似于单引号字符串的。Nowdoc 结构很象 heredoc 结构,但是 nowdoc 中不进行解析操作。这种结构很适合用于嵌入 PHP 代码或其它大段文本而无需对其中的特殊字符进行转义。
echo <<<'EOT'
My name is "$name".
This should not print a capital 'A': \x41
EOT;
输出:
My name is "$name".
This should not print a capital 'A': \x41
参考文章:PHP:String