2012-04-12 50 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