问题
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.
Is there a graceful way to handle both of these cases?
回答1:
The easiest way of dealing with this is turning all line breaks \n into <br> line breaks. In PHP for example, this is done using the nl2br() function.
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. 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....
回答2:
You can use the php function nl2br() It transforms line breaks into
elements
回答3:
Convert newline characters to <br /> tags explicitly, and let the browser word-wrap the text normally. That preserves the breaks the visitor entered, without harming other paragraphs.
回答4:
You could replace line breaks with HTML line breaks.
Replace "\r\n" or "\n" (depending on the browser and platform, check first for longer one) with <br/>.
回答5:
I would normally replace all CR/LF with LF, and then replace all LF with <br />. You can then render this text inside any HTML container you want and let it flow naturally.
来源:https://stackoverflow.com/questions/3007024/best-practices-displaying-text-that-was-input-via-multi-line-text-box