看到很多开源系统中,控制中要输出一大长串的HTML代码,不可避免的存在字符之间的转义问题:(php字符串中有两种结构可以很好地解决这个问题)
一、1. heredoc 结构
看看php手册对此的介绍:
第三种表达字符串的方法是用 heredoc 句法结构:<<<。在该运算符之后要提供一个标识符,然后换行。接下来是字符串string本身,最后要用前面定义的标识符作为结束标志。
结束时所引用的标识符必须在该行的第一列,而且,标识符的命名也要像其它标签一样遵守 PHP 的规则:只能包含字母、数字和下划线,并且必须以字母和下划线作为开头。
先来看一个例子:
$tpl = <<<tpl
<div class="right-head">
{$key}
</div>
<div class="right-body">
<div class="right-body-block">
<div class="prev-block">
{$img}
</div>
<p class="file-info-item">
外链地址:<input class="file-share-link" type="text" readonly="readonly" value="{$this->qiniu->downlink($key)}">
</p>
<p class="file-info-item">
最后更新时间:<span>{$time}</span>
</p>
<p class="file-info-item">
文件大小:<span class="file-size">{$filesize}</span>
</p>
</div>
</div>
tpl;//必须顶格,不能有空格
再来一个手册中的例子
1)开始标记和结束标记使用相同的字符串,通常以大写字母来写。
2)开始标记后不能出现空格或多余的字符。
3)结束标记必须顶头写,不能有缩进和空格,且在结束标记末尾要有分号 。
二、nowdoc 结构
就象 heredoc 结构类似于双引号字符串,Nowdoc 结构是类似于单引号字符串的。Nowdoc 结构很象 heredoc 结构,但是 nowdoc 中不进行解析操作。这种结构很适合用于嵌入 PHP 代码或其它大段文本而无需对其中的特殊字符进行转义。与 SGML 的 <![CDATA[ ]]> 结构是用来声明大段的不用解析的文本类似,nowdoc 结构也有相同的特征。
一个 nowdoc 结构也用和 heredocs 结构一样的标记 <<<, 但是跟在后面的标识符要用单引号括起来,即 <<<‘EOT’。Heredoc 结构的所有规则也同样适用于 nowdoc 结构,尤其是结束标识符的规则。
<?php
$str = <<<EOD
Example of string
spanning multiple lines
using heredoc syntax.
EOD;
/* 含有变量的更复杂示例 */
class foo
{
var $foo;
var $bar;
function foo()
{
$this->foo = 'Foo';
$this->bar = array('Bar1', 'Bar2', 'Bar3');
}
}
$foo = new foo();
$name = 'MyName';
echo <<<EOT
My name is "$name". I am printing some $foo->foo.
Now, I am printing some {$foo->bar[1]}.
This should print a capital 'A': \x41
EOT;
?>
以上例程会输出:
My name is "MyName". I am printing some Foo.
Now, I am printing some Bar2.
This should print a capital 'A': A
$str = <<<'EOD'
Example of string
spanning multiple lines
using nowdoc syntax.
EOD;
/* 含有变量的更复杂的示例 */
class foo
{
public $foo;
public $bar;
function foo()
{
$this->foo = 'Foo';
$this->bar = array('Bar1', 'Bar2', 'Bar3');
}
}
$foo = new foo();
$name = 'MyName';
echo <<<'EOT'
My name is "$name". I am printing some $foo->foo.
Now, I am printing some {$foo->bar[1]}.
This should not print a capital 'A': \x41
EOT;
?>
以上例程会输出:
My name is "$name". I am printing some $foo->foo.
Now, I am printing some {$foo->bar[1]}.
This should not print a capital 'A': \x41
三、heredoc和nowdoc 区别
1) heredoc使用 <<< EOT 的标示符,而nowdoc使用 <<< ‘EOT’ 这样的标示符
2)heredoc是动态的 nowdoc是静态的
原创文章,转载请注明: 转载自HSBLOG
本文链接地址: PHP字符串的heredoc和nowdoc语法结构