Coder Perfect

TextArea Line Breaks Should Be Preserved

Problem

To allow users to enter comments, I’m utilising a textarea. When the user inserts new lines, however, the new lines do not display when the output is printed. Is there a way to keep the line breaks from disappearing?

Is there a way to keep the line breaks?

Asked by Hirvesh

Solution #1

There are two options for this:

Answered by superUntitled

Solution #2

What I utilize is as follows:

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

The text to be shown is stored in $text. The returned text from nl2br and htmlentities is $textToOutput, which can be safely displayed in the html context. ENT QUOTES can handle both double and single quotes, thus you won’t have any problems.

Answered by hiroki

Solution #3

I came up with my own response: The problem is solved by calling this function using the data from the textarea:

function mynl2br($text) { 
   return strtr($text, array("\r\n" => '<br />', "\r" => '<br />', "\n" => '<br />')); 
} 

More here: http://php.net/nl2br

Answered by Hirvesh

Solution #4

I’m using this two approach steps to save the same text that’s in the textarea in mysql, and I can also display plain text at a later point…..

step 1:

$status=$_POST['status'];<br/>
$textToStore = nl2br(htmlentities($status, ENT_QUOTES, 'UTF-8'));

Enter $textToStore in the query….

step 2:

It works

Answered by Jayendra Bariya

Solution #5

This works:

function getBreakText($t) {
    return strtr($t, array('\\r\\n' => '<br>', '\\r' => '<br>', '\\n' => '<br>'));
}

Answered by UbiQue

Post is based on https://stackoverflow.com/questions/5048849/preserve-line-breaks-from-textarea