Preserving Line Breaks from TextArea Input
When utilizing a textarea for user input, you may encounter the challenge of preserving line breaks during output. New lines entered in the textarea often disappear once displayed, leaving your text as a continuous stream.
Solution 1: PHP nl2br() Function
PHP provides the nl2br() function, which specifically addresses this issue. It converts new lines (rn) into HTML line breaks (
) within a given string.
For instance:
$input = "This\r\nis\n\ra\nstring\r"; echo nl2br($input);
Output:
This<br /> is<br /> a<br /> string<br />
Solution 2: Tags</strong></p>
<p>Another effective approach involves wrapping the user input within <pre class="brush:php;toolbar:false">
tags. These tags essentially preserve the formatting and line breaks of the input, displaying it exactly as entered.
Refer to the W3C Wiki for more information on the
element: https://www.w3.org/wiki/HTML/Elements/preThe above is the detailed content of How to Preserve Line Breaks from Textarea Input in PHP and HTML?. For more information, please follow other related articles on the PHP Chinese website!