Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

line breaks in a textarea

I know when saving a textarea you can use the nl2br() or str_replace to change the /n to br tags etc. However what im not sure about how to insert line breaks into a textarea. I cant seem to find much about putting the data back into a textarea with those line breaks.

For example I have a form where users can update fields. So the user may enter:

foo bar baz 

When that is saved to the database it would be saved as:

foo<br />bar<br />baz<br /> 

Now when that user goes back to that form after a page refresh all the fields are automatically populated with their previous data by taking the data from the database.

However the textarea shows the br tags as text instead of adding in the line breaks. i also tried changing the br tags to /n hoping the textarea would interpret these as line breaks but no joy. As well as this I also tried escaping etc.

So my questions are can this be done? Or more importantly can it be done using HTML/PHP (im using smarty). If that isnt possible can it be done using javascript?

Examples would be appreciated.

thanks for reading

like image 775
fl3x7 Avatar asked Jun 25 '11 21:06

fl3x7


People also ask

Which character defines a new line in the textarea?

Talking specifically about textareas in web forms, for all textareas, on all platforms, \r\n will work.

Can we use DIV inside textarea?

No, it is not possible(it will not render the UI).

How do you enter a new line in text?

To add spacing between lines or paragraphs of text in a cell, use a keyboard shortcut to add a new line. Click the location where you want to break the line. Press ALT+ENTER to insert the line break.

How do you preserve line breaks in a div?

The easiest solution is to simply style the element you're inserting the text into with the following CSS property: white-space: pre-wrap; This property causes whitespace and newlines within the matching elements to be treated in the same way as inside a <textarea> .


2 Answers

Don't do nl2br when you save it to the database. Do nl2br when you're displaying the text in HTML. I can strongly recommend to not store any HTML formatting in the database (unless you're using a rich HTML editor as well, in which case it would be silly not to).

A newline \n will just become a newline in the textarea.

like image 157
Halcyon Avatar answered Oct 07 '22 17:10

Halcyon


You could use str_replace to replace the <br /> tags into end of line characters.

str_replace('<br />', PHP_EOL, $textarea); 

Alternatively, you could save the data in the database without calling nl2br first. That way the line breaks would remain. When you display as HTML, call nl2br. An additional benefit of this approach is that it would require less storage space in your database as a line break is 1 character as opposed to "<br />" which is 6.

like image 34
Francois Deschenes Avatar answered Oct 07 '22 18:10

Francois Deschenes