简体   繁体   English

最佳做法:显示通过多行文本框输入的文本

[英]Best practices: displaying text that was input via multi-line text box

I have a multi-line text box. 我有一个多行文本框。 When users simply type away, the text box wraps the text, and it's saved as a single line. 当用户只是简单地键入内容时,文本框将包装文本,并将其保存为一行。 It's also possible that users may enter line breaks, for example when entering a "bulleted" lists like: 用户也可能输入换行符,例如,在输入“项目符号”列表时,例如:

Here are some suggestions:
 - fix this
 - remove that
 - and another thing

Now, the problem occurs when I try to display the value of this field. 现在,当我尝试显示此字段的值时会出现问题。 In order to preserve the formatting, I currently wrap the presentation in <pre> - this works to preserve user-supplied breaks, but when there's a lot of text saved as a single line, it displays the whole text block as single line, resulting in horizontal scrolling being needed to see everything. 为了保留格式,我目前将演示文稿包装在<pre> -可以保留用户提供的休息时间,但是当很多文本保存为一行时,它将整个文本块显示为一行,结果需要水平滚动才能看到所有内容。

Is there a graceful way to handle both of these cases? 是否有一种优雅的方式来处理这两种情况?

The easiest way of dealing with this is turning all line breaks \\n into <br> line breaks. 解决此问题的最简单方法是将所有换行符\\n转换为<br>换行符。 In PHP for example, this is done using the nl2br() function. 例如,在PHP中,这是使用nl2br()函数完成的。

If you want something a bit more fancy - like the list you quote getting converted into an actual HTML <ul> for example - you could consider a simple "language" like Markdown that SO uses. 如果您想要更多花哨的内容(例如,您引用的列表转换成实际的HTML <ul> ,则可以考虑使用SO这样的简单“语言”,例如Markdown It comes with natural, simple rules like 它带有自然,简单的规则,例如

# Heading 1
## Heading 2
### Heading 3

* Unordered List item
* Unordered List item

1. Numbered List item 
2. Numbered List item

etc.... 等等....

You can use the php function nl2br() It transforms line breaks into 您可以使用php函数nl2br()将换行符转换为
elements 分子

Convert newline characters to <br /> tags explicitly, and let the browser word-wrap the text normally. 将换行符显式转换为<br />标记,然后让浏览器正常对文本进行自动换行。 That preserves the breaks the visitor entered, without harming other paragraphs. 这样可以保留访客输入的休息时间,而不会损害其他段落。

You could replace line breaks with HTML line breaks. 您可以将换行符替换为HTML换行符。

Replace "\\r\\n" or "\\n" (depending on the browser and platform, check first for longer one) with <br/> . 替换"\\r\\n""\\n" (取决于浏览器和平台,首先检查较长的一个)与<br/>

I would normally replace all CR/LF with LF , and then replace all LF with <br /> . 我通常将所有CR/LF替换为LF ,然后将所有LF替换为<br /> You can then render this text inside any HTML container you want and let it flow naturally. 然后,您可以在所需的任何HTML容器中呈现此文本,并使其自然流动。

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

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