PHP新行问题

joh*_*ack 0 php syntax

简单的问题莫名其妙...

我有一个功能:

function spitHTML() {
    $html = '
    <div>This is my title</div>\n
    <div>This is a second div</div>';

    return $html
}

echo $spitHTML();
Run Code Online (Sandbox Code Playgroud)

为什么这实际上吐出了\n?

Dan*_*oap 5

单引号字符串中使用的反斜杠不能用作转义字符(除了单引号本身).

$string1 = "\n"; // this is a newline
$string2 = '\n'; // this is a backslash followed by the letter n
$string3 = '\''; // this is a single quote
$string3 = "\""; // this is a double quote
Run Code Online (Sandbox Code Playgroud)

那么为什么要使用单引号呢?答案很简单:如果你想打印HTML代码,其中自然有很多双引号,用单引号包装字符串更具可读性:

$html = '<div class="heading" style="align: center" id="content">';
Run Code Online (Sandbox Code Playgroud)

这要好得多

$html = "<div class=\"heading\" style=\"align: center\" id=\"content\">";
Run Code Online (Sandbox Code Playgroud)

除此之外,由于PHP不必解析变量和/或转义字符的单引号字符串,因此它会更快地处理这些字符串.

就个人而言,我总是使用单引号并附加双引号中的换行符.这看起来像

$text = 'This is a standard text with non-processed $vars followed by a newline' . "\n";
Run Code Online (Sandbox Code Playgroud)

但这只是一个品味问题:o)