保留 TextArea 的换行符

新手上路,请多包涵

我正在使用文本区域使用户能够输入评论。但是,如果用户输入新行,则输出时不会出现新行。有没有办法让换行符留下来。

知道如何保留换行符吗?

原文由 Hirvesh 发布,翻译遵循 CC BY-SA 4.0 许可协议

阅读 378
2 个回答

两种解决方案:

  1. PHP函数 nl2br()

例如,

    echo nl2br("This\r\nis\n\ra\nstring\r");

   // will output
   This<br />
   is<br />
   a<br />
   string<br />

  1. 将输入包装在 <pre></pre> 标签中。

请参阅: W3C Wiki - HTML/Elements/pre

原文由 superUntitled 发布,翻译遵循 CC BY-SA 3.0 许可协议

这是我用的

$textToOutput = nl2br(htmlentities($text, ENT_QUOTES, 'UTF-8'));

$text is the text that needs to be displayed $textToOutput is the returned text from nl2br and htmlentities so it can be safety displayed in the html上下文。

ENT_QUOTES 将同时转换双引号和单引号,因此您不会遇到这些问题。

原文由 hiroki 发布,翻译遵循 CC BY-SA 4.0 许可协议

推荐问题