【问题标题】:How to add new line in php echo如何在php echo中添加新行
【发布时间】:2015-01-15 07:38:49
【问题描述】:

我数据库中故事内容的文本是:

I want to add\r\nnew line

(无引号)

当我使用时:

echo nl2br($story->getStoryContent());

br 替换\r\n,它不起作用。浏览器仍然显示\r\n。当我查看源代码时,\r\n 仍然存在,br 也无处可寻。这很奇怪,因为当我使用以下简单代码测试函数 nl2br 时:

echo nl2br("Welcome\r\nThis is my HTML document");

确实有效。你能告诉我为什么它不起作用吗?非常感谢。

【问题讨论】:

  • 你试过echo preg_replace('/\r\n/', '<br/>', $story->getStoryContent());吗?
  • 感谢您的回复。我尝试了你的建议,但它不起作用。
  • 那么您似乎不是在寻找\r\n。尝试相同的方法并改为寻找PHP_EOL

标签: php nl2br


【解决方案1】:

下面的 sn-p 使用了一种你可能更喜欢的技术,如下:

<?php

$example = "\n\rSome Kind\r of \nText\n\n";


$replace = array("\r\n", "\n\r", "\r", "\n");
$subs    = array("","","","");

$text = str_replace($replace, $subs, $example );
var_dump($text); // "Some Kind of Text"

现场演示here

我怀疑你是否需要“\n\r”,但我把它留了下来,以防你觉得真的有必要。 这是通过在每种情况下将行终止字符串数组替换为空字符串来实现的。

【讨论】:

    【解决方案2】:

    我发现答案很简单。我只是使用

    $text = $this->storyContent;
    $text = str_replace("\\r\\n","<br>",$text);
    $text = str_replace("\\n\\r","<br>",$text);
    $text = str_replace("\\r","<br>",$text);
    $text = str_replace("\\n","<br>",$text);
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2016-06-03
      相关资源
      最近更新 更多