【问题标题】:Odd behavior for replacing newlines in PHP在 PHP 中替换换行符的奇怪行为
【发布时间】:2012-04-25 02:09:59
【问题描述】:

我在 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 调用分别用于 \n、\r\n 和 \r

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

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

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

echo nl2br($text);

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

有什么想法吗?

【问题讨论】:

  • 你有一行重复了 3 次...你的意思是 \r\n 在第一个,\r 在第二个和 \n 在3rd 一个?
  • 另外,您将在第一种方法中替换为null,但在其他方法中替换为一个空格。这是故意的吗?
  • 弗兰克,是的,这是一个巨大的错字,对不起! jb,是的,这是故意的,但我希望每个人在实际删除换行符时表现相似。

标签: php string str-replace


【解决方案1】:

来自文本区域的文本总是\r\n换行符。

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

请参阅the spec 了解更多信息。

【讨论】:

  • Text coming from an textarea ALWAYS has \r\n linebreaks - 这是真的吗?我一直认为它使用操作系统使用的行尾类型......好吧,你每天都会学到一些东西。并且传递null 作为替换与传递'' 相同,所以你不妨这样做。
  • 让我为您获取规格。 1秒请
  • @DaveRandom 学习永远不会太老 ;) 这绝不是麻烦
  • 如果 textarea 中的文本没有标准化,它将遵循 用户的计算机的操作系统约定,而不是服务器的。
  • 鉴于我上面所做的编辑(巨大的错字,对不起大家!),$text = str_replace("\r\n", '', $text);实际上没有用。
【解决方案2】:

你应该使用:

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

【讨论】:

    猜你喜欢
    • 2012-08-31
    • 1970-01-01
    • 1970-01-01
    • 2012-02-24
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2016-10-26
    • 1970-01-01
    相关资源
    最近更新 更多