在 PHP 中替换换行符的奇怪行为 [英] Odd behavior for replacing newlines in PHP
问题描述
我在使用 PHP 时遇到了一些奇怪的行为.我有一个来自 输入的文本字符串,它似乎是:
I've encountered some strange behavior with PHP. I have a string of text from a <textarea/>
input and it seems that:
$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
没有成功删除换行符.我什至尝试添加:
does NOT successfully remove newlines. I even tried adding:
$text = str_replace(PHP_EOL, " ", $text);
但它并没有解决问题.我知道我用空格而不是空替换换行符,但我希望这也能工作.完成 3-4 次 str_replace() 调用后,如果我:
but it doesn't fix the problem. I know I'm replacing the newlines with a space instead of null, but I would expect this to also work. After doing the 3-4 str_replace() calls, if I:
echo nl2br($text);
它实际上确实找到了一些剩余的换行符.
it does in fact find some remaining newline characters.
有什么想法吗?
推荐答案
来自文本区域的文本总是有 \r\n
换行符.
Text coming from an textarea ALWAYS has \r\n
linebreaks.
所以你应该只做 $text = str_replace("\r\n", '', $text);
有关详细信息,请参阅规范.
See the spec for more info.
这篇关于在 PHP 中替换换行符的奇怪行为的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!