2009-09-09 56 views
0

簡單的問題,莫名其妙的我...PHP新線的問題

我有一個函數:

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

    return $html 
} 

echo $spitHTML(); 

這是爲什麼居然吐出了\ n的?

回答

4

因爲你使用單引號 - 更改爲雙引號,它會表現爲你所期望

查看文檔Single quoted strings。在單引號字符串中使用

+0

嘆息... ... DUH我應該已經試過了。但是,真正的區別是什麼?我想我只會張貼另一個問題哈哈......謝謝! – johnnietheblack 2009-09-09 22:52:56

+3

@johnnietheblack,閱讀文檔! – strager 2009-09-09 22:54:28

3

改變「爲」:)(在那之後,所有的特殊字符和可變注意到)

$html = " 
<div>This is my title</div>\n 
<div>This is a second div</div>"; 
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 

那爲什麼要用單引號呢?答案很簡單:如果你要打印,例如HTML代碼,其中自然有很多雙引號的,包裹在單引號的字符串更可讀:

$html = '<div class="heading" style="align: center" id="content">'; 

這是更好比

$html = "<div class=\"heading\" style=\"align: center\" id=\"content\">"; 

除此之外,因爲PHP沒有解析的變量和/或轉義字符單引號字符串,它處理這些字符串快一點。

就我個人而言,我總是使用單引號並在雙引號中附加換行符。這則看起來像

$text = 'This is a standard text with non-processed $vars followed by a newline' . "\n"; 

但是,這只是一個品味的問題:O)

+0

+1 - 很好的解釋 – karim79 2009-09-09 23:25:25