2

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?

5 Answers 5

3

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....

1
  • I don't think my users would understand Markdown, unfortunately.
    – chris
    Jun 9, 2010 at 16:09
1

You can use the php function nl2br() It transforms line breaks into
elements

1

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.

1

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/>.

0

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.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.