在 PHP 中替换换行符的奇怪行为


Odd behavior for replacing newlines in PHP

我在PHP上遇到了一些奇怪的行为。我有一个来自<textarea/>输入的文本字符串,似乎:

$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调用分别用于',''r'和''r

未成功删除换行符。我什至尝试添加:

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

但它并不能解决问题。我知道我正在用空格而不是 null 替换换行符,但我希望这也有效。执行 3-4 个 str_replace() 调用后,如果我:

echo nl2br($text);

事实上,它确实找到了一些剩余的换行符。

有什么想法吗?

来自

文本区域的文本总是'r'n换行符。

所以你应该做$text = str_replace("'r'n", '', $text);

有关详细信息,请参阅规范。

你应该使用:

$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)