user1260310
user1260310

Reputation: 2227

MYSQL PHP Save linebreaks in textarea for later display

I am collecting text from a textarea. The text has line breaks in it. I then save it to a database.

However when I retrieve it from the database and display it back in a textarea for editing, the line breaks are gone and the text turns into one long run-on string.

I would like the line breaks originally there to reappear. How can I make the line breaks appear as they should when inserted back into a textarea?

Note: I cannot just convert them to a <br> because this is going inside a textarea where <br> elements would not get rendered, but just written out as text. I want the actual line breaks.

Upvotes: 3

Views: 10142

Answers (4)

J Charles
J Charles

Reputation: 390

Everyone is suggesting to convert the line breaks to <br />, however as you stated in your question that's not what you want. You want to display the line breaks in the textarea again. So, what you need here is stripcslashes() - this will strip away \n and give you what you're after, being line breaks in your textarea, not html <br /> tags in the textarea:

PHP: stripcslashes

Usage:

echo stripcslashes($input_text);

Upvotes: 5

Nathan
Nathan

Reputation: 7

str_replace() doesn't go like this:

echo str_replace($data, "\n", "<br />");

It goes like this:

str_replace("SEARCH_FOR","REPLACE_WITH",STRING);

In the sense that SEARCH_FOR is what you are trying to find, REPLACE_WITH is what you want to replace with, and STRING is the variable you are using (such as $data).

Upvotes: -1

Carlos
Carlos

Reputation: 238

You coud use something like this:

echo nl2br($someText);

Upvotes: 0

ariefbayu
ariefbayu

Reputation: 21979

This is what I usually do when dealing with this kind of problem:

  1. Save whatever data receiver in form. This mean, if user use newline, store it that way. Don't change it.
  2. Upon displaying data, convert every newline to <br />:

    echo str_replace("\n", "<br />", $data);
    

Using this technique, you can preserve whatever formatting data used by your user in textarea.

Upvotes: -1

Related Questions