Keep Line Breaks from Textarea
Solution 1
you want to utilize the white-space css attribute http://www.w3schools.com/cssref/pr_text_white-space.asp
So you'll have something like
<p class="whitespace"><?= $input_from_textarea ?></p>
with css:
.whitespace {
white-space: pre-wrap;
}
Do not manually clean your input replacing new line elements with break tags. It makes your data less reusable and is a lot more work.
You can use the php function nl2br()
but it does not give you as much control as manipulating the display through css.
Solution 2
You can use echo nl2br( $string)
to convert \n
to <br>
HTML line break.
Solution 3
HTML collapses any amount of whitespace (except non breaking space) including new lines to a single space. In order to maintain new lines, you will need to replace new lines with <br>
or use <pre>
tags or use one of the white-space CSS rules designed to control this behaviour.
Solution 4
use nl2br() method to ratain your . nl2br($text); for more quires check this http://www.php.net/manual/en/function.nl2br.php
William
Updated on June 18, 2022Comments
-
William almost 2 years
I am getting input from a user in a form via PHP in a WordPress site (an address specifically) and I want to be able to display the information that I gather with the same line breaks (separating out the different components of the address) on a different page. It displays correctly if I put it into a textarea, but if I get the data and echo it into a div by itself, it doesn't maintain the line breaks. What can I do?
-
Charles Ouellet almost 11 yearsThis answer should be accepted!