繁体   English   中英

如何在php echo中添加新行

[英]How to add new line in php echo

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

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");

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

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

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

以下代码片段使用了您可能更喜欢的一种技术,如下所示:

<?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"

现场演示在这里

我怀疑您是否需要“ \\ n \\ r”,但为了您确实有必要,我将其保留。 这通过使行终止字符串的数组在每种情况下都替换为空字符串而起作用。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM