2012-04-12 46 views
-1

我遇到了PHP的一些奇怪行爲。我的文字從<textarea/>輸入一個字符串,它似乎是:在PHP中替換換行符的行爲奇怪

$text = str_replace(array("\r\n", "\r", "\n"), null, $text); 

成功地消除了換行,而

$text = str_replace("\n", " ", $text) 
$text = str_replace("\r\n", " ", $text) 
$text = str_replace("\r", " ", $text) 

編輯:三個str_replace函數調用。以上是\ n,\ r \ n和\ r

不能成功刪除換行符。我甚至嘗試加入:

$text = str_replace(PHP_EOL, " ", $text); 

但它不能解決問題。我知道我用空格而不是null替換換行符,但我希望這也能起作用。做3-4 str_replace()函數調用後,如果我:

echo nl2br($text); 

它實際上找到一些剩餘的換行符。

任何想法?

+2

你有一條線重複了3次......你的意思是第一個是'\ r \ n',第二個是'\ r',而第三個是'n'。 – 2012-04-12 17:19:50

+0

另外,您在第一種方法中用'null'替換,但在其他方法中只有一個空格。這是故意的嗎? – 2012-04-12 17:21:02

+0

弗蘭克,是的,這是一個巨大的錯字,對不起! jb,是的,這是故意的,但我希望每個人在實際移除換行符時行爲相似。 – vette982 2012-04-12 18:29:43

回答

1

你應該使用:

$text = str_replace("\r\n", " ", $text) 
$text = str_replace("\r", " ", $text) 
$text = str_replace("\n", " ", $text) 

$text = str_replace("\r\n", null, $text) 
$text = str_replace("\r", null, $text) 
$text = str_replace("\n", null, $text) 
3

文本從textarea的未來總是\r\n換行符。

所以,你應該只是做$text = str_replace("\r\n", '', $text);

更多信息,請參見the spec

+1

'文本來自textarea總是有\ r \ n linebreaks' - 這是真的嗎?我總是認爲它使用了操作系統使用的行結束類型......嗯,你每天都會學到一些東西。並且傳遞'null'作爲替換與傳遞''''相同,所以你可以這樣做。 – DaveRandom 2012-04-12 17:19:14

+0

Lemme爲你準備好規格。 1秒請 – PeeHaa 2012-04-12 17:19:42

+0

@DaveRandom更新:-) – PeeHaa 2012-04-12 17:20:44