user2981188
user2981188

Reputation:

<br> stored in mysql field but no line break when echo

I am storing data in a field named message. An example of this field is:

<br /><br />

shane!

<br /><br />

****** Original Message ******

Test Back


<br /><br />


****** Original Message ******

test

When I echo this into a <textarea> field, it is displayed as this:

shane! ****** Original Message ****** Test Back ****** 
Original Message ****** test

How do I echo this to include the line breaks?

Upvotes: 1

Views: 3195

Answers (3)

S&#233;bastien
S&#233;bastien

Reputation: 12139

When outputting to a textarea you must call htmlentities htmlspecialchars if your text contains HTML.

<textarea><?php echo htmlspecialchars($text); ?></textarea>

That will convert your <br /> to &lt;br /&gt;. If you leave the <br /> unencoded they will simply be interpreted as HTML.

If your goal is to display <br /> or other HTML in the textarea as it is written in the database you must escape all code that would otherwise be interpreted as HTML.

edit

If you want to output line breaks instead of <br /> you can use str_replace:

<textarea><?php echo str_replace('<br />', "\r\n", $textarea); ?></textarea>

But remember that all other HTML will be interpreted and not displayed. I think you should solve your problem at the source and store the CRLF in the database if you don't need the HTML.

Upvotes: 3

Choudhury A. M.
Choudhury A. M.

Reputation: 5202

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

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

Upvotes: 2

Akira
Akira

Reputation: 4071

The tag does not accept HTML code inside of it. Instead, you need to format your code as in a plain text file. Check this example:

http://www.w3schools.com/tags/tryit.asp?filename=tryhtml_textarea

Now replace the source code with the following:

<!DOCTYPE html>
<html>
<body>

<textarea rows="4" cols="50">
At w3schools.com you will learn how to make a website.



We offer free tutorials in all web development technologies.
</textarea>

</body>
</html>

You will see that formatting inside of the textarea works pretty much like the tag. So the answer to your question is that you need to replace each
by a newline character.

Upvotes: 0

Related Questions