在PHP中是否可以像在C中一样转义字符串中的换行符?

Pet*_*uza 1 php c newline escaping

在C中,您可以在转义换行符的下一行中继续使用字符串文字:

char* p = "hello \
new line.";

$p = "hello \
new line.";

IE反斜杠字符构成字符串的一部分.在这种情况下,有没有办法在PHP中获取C行为?

JYe*_*ton 7

是否可以简单地连接您的字符串,如下所示:

$p = "hello " .
     "new line.";
Run Code Online (Sandbox Code Playgroud)


Ala*_*orm 6

有几种方法可以在PHP中执行相似的操作,但无法使用延续终止符来完成此操作.

对于初学者,您可以在下一行继续使用字符串而不使用任何特定字符.以下内容在PHP中有效且合法.

$foo = 'hello there two line 
string';

$foo = 'hello there two line 
    string';    
Run Code Online (Sandbox Code Playgroud)

第二个例子应该是这种方法的缺点之一.除非你将其余的行留给了jusity,否则你需要在字符串中添加额外的空格.

第二种方法是使用字符串连接

$foo = 'hell there two line'.
'string';

$foo = 'hell there two line'.
    'string';   
Run Code Online (Sandbox Code Playgroud)

上面的两个例子都会导致创建的字符串相同,换句话说就是没有额外的空格.这里的权衡是你需要执行字符串连接,这不是免费的(虽然使用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;
Run Code Online (Sandbox Code Playgroud)

你会得到与第一个例子相同的领先空白问题,但是有些人发现HEREDOC更具可读性.