tags:

views:

111

answers:

5

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  A: 

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

greg0ire
+1  A: 

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.

VoteyDisciple
+2  A: 

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

Pekka
I don't think my users would understand Markdown, unfortunately.
chris
A: 

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.

RedFilter
A: 

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

Developer Art