PHP 字符串中的变量替换机制
将变量插入字符串主要有两种途径:基础方式和进阶方式。
基础方式是将变量名直接置于双引号字符串或 heredoc 结构中:
$who = 'Kilroy';
$where = 'here';
echo "$who was $where";
Kilroy was here
进阶方式则是用大括号包裹待替换的变量。此举旨在消除歧义或实现数组索引查找,其经典用途是将变量名与周围文本明确分隔:
$n = 12;
echo "You are the {$n}th person";
You are the 12th person
若省略大括号,PHP 引擎会尝试解析名为 $nth 的变量。
不同于部分 Shell 环境,PHP 字符串中的变量仅进行一次解析,即仅在双引号字符串中进行处理,随后结果作为最终字符串值:
$bar = 'this is not printed';
$foo = '$bar'; // 单引号
print("$foo"); //双引号
$bar
4.1.2 用单引号括起来的字符串
Single-Quoted Strings
单引号字符串不进行变量替换。由于字符串字面量由单引号界定,其中的变量名不会被解析:
$name = 'Fred';
$str = 'Hello, $name'; // single-quoted 用单引号括起来
echo $str;
Hello, $name
在单引号字符串中,仅支持两个转义序列:\'(表示单引号)和 \\(表示反斜杠)。其他任何反斜杠组合均被解释为普通反斜杠字符:
$name = 'Tim O\'Reilly'; //转义的单引号
echo $name;
$path = 'C:\\WINDOWS'; //转义的反斜杠
echo $path;
$nope = '\n'; // 不是转义序列
echo $nope;
Tim O'Reilly
C:\WINDOWS
\n
4.1.3 用双引号括起来的字符串
Double-Quoted Strings
双引号字符串支持变量解析及多种转义序列。表 4-1 列出了双引号字符串中 PHP 认可的转义序列。
表 4-1:用双引号括起来的字符串中的转义序列
转义序列 字符含义
\”
双引号
\n
换行
\r
回车
\t
制表符
\\
反斜杠
\$
美元符号
\{
左大括号
\}
右大括号
\[
左中括号
\]
右中括号
\0 through \777
用八进制表示的 ASCII 字符
\x0 through \xFF
用十六进制表示的 ASCII 字符
若在双引号字符串中发现未定义的转义序列(如反斜杠后跟随非表 4-1 中的字符),该序列将被忽略;若错误级别设置为 E_NOTICE,则会生成警告:
$str = "What is \c this?"; // 未知的转义序列
echo $str ;
What is \c this?
4.1.4 字符串定界
Here Documents heredoc
使用 heredoc 语法可将多行字符串直接嵌入代码,示例如下:
$clerihew = <<< End_Of_Quote
Sir Humphrey Davy
Abominated gravy.
He lived in the odium
Of having discovered sodium.
End_Of_Quote;
echo $clerihew;
Sir Humphrey Davy
Abominated gravy.
He lived in the odium
Of having discovered sodium.
<<< 符号(常称字符串定界符)告知 PHP 解析器正在书写 heredoc。<<< 与标识符(本例为 End_Of_Quote)间须有空格以区分标识符。后续行即为引用文本,直至遇到仅含标识符的行为止。
可在终止标识符后加分号以结束语句,如前例所示。若在复杂表达式中使用 heredoc,需分行书写:
printf(<<< Template
%s is %d years old.
Template
, “Fred”, 35);
heredoc 内的单引号和双引号被视为普通字符而被跳过:
$dialogue = <<< No_More
“It's not going to happen!” she fumed.
He raised an eyebrow. “Want to bet?”
No_More;
echo $dialogue;
“It's not going to happen!” she fumed.
He raised an eyebrow. “Want to bet?”
heredoc 中的空白字符同样被保留:
$ws = <<< Enough
boo
hoo
Enough;
// $ws = ” boo\n hoo\n”;
因终止符前的换行符会被移除,以下两赋值等价:
$s = 'Foo';
// same as 和下面的相同
$s = <<< End_of_pointless_heredoc
Foo
End_of_pointless_heredoc;
若希望 heredoc 结尾包含换行符,需手动添加:
$s = <<< End
Foo
End;
//注意 Foo 后面跟一个空行,不可删除