【发布时间】:2009-08-26 19:59:56
【问题描述】:
在 C 中,您可以在下一行继续字符串文字,转义换行符:
(我的 C 有点生锈,这可能不是 100% 准确的)char* p = "hello \
new line.";
但在 php 中,反斜杠实际上是:
$p = "hello \
new line.";
I.E.反斜杠字符构成字符串的一部分。 在这种情况下,有没有办法在 PHP 中获取 C 行为?
【问题讨论】:
在 C 中,您可以在下一行继续字符串文字,转义换行符:
(我的 C 有点生锈,这可能不是 100% 准确的)char* p = "hello \
new line.";
但在 php 中,反斜杠实际上是:
$p = "hello \
new line.";
I.E.反斜杠字符构成字符串的一部分。 在这种情况下,有没有办法在 PHP 中获取 C 行为?
【问题讨论】:
是否可以像这样简单地连接您的字符串:
$p = "hello " .
"new line.";
【讨论】:
在 PHP 中有一些类似的方法可以做到这一点,但没有办法使用延续终止符来做到这一点。
对于初学者,您可以在下一行继续您的字符串,而无需使用任何特定字符。以下在 PHP 中是有效且合法的。
$foo = 'hello there two line
string';
$foo = 'hello there two line
string';
第二个例子应该是这种方法的缺点之一。除非您对剩余的行保持公正,否则您将在字符串中添加额外的空格。
第二种方法是使用字符串连接
$foo = 'hell there two line'.
'string';
$foo = 'hell there two line'.
'string';
以上两个示例都将导致创建相同的字符串,换句话说,没有额外的空格。这里的权衡是您需要执行字符串连接,这不是免费的(尽管使用 PHP 的可变字符串和现代硬件,您可以在开始注意到性能下降之前摆脱大量连接)
最后是 HEREDOC 格式。与第一个选项类似,HEREDOC 也允许您将字符串拆分为多行。
$foo = <<<TEST
I can go to town between the the start and end TEST modifiers.
Wooooo Hoooo. You can also drop $php_vars anywhere you'd like.
Oh yeah!
TEST;
您会遇到与第一个示例相同的前导空格问题,但有些人发现 HEREDOC 更具可读性。
【讨论】:
在 PHP 中,您可以简单地使用字符串继续换行。
例如。
<?php
$var = 'this is
some text
in a var';
?>
【讨论】:
简短的回答是,您不能像在 C 中那样轻松地做到这一点,您需要连接(最好):
$p = "This is a long".
" non-multiline string";
或之后删除换行符(糟糕,不要这样做):
$p = "This will contain the newlines
before this line";
//for instance str_replace() can remove the newlines
【讨论】: