When capturing user input through a textarea element, it's often desirable to preserve line breaks entered by the user. However, by default, these line breaks are stripped from the output.
One simple solution is to utilize the PHP nl2br() function. This function converts line breaks (n or rn) into HTML
tags, effectively preserving them in the output.
For instance:
<?php $comment = "This\r\nis\n\ra\nstring"; echo nl2br($comment); ?>
This code will output:
This<br /> is<br /> a<br /> string<br />
Another approach is to wrap the textarea input within a
tag. This tag interprets line breaks as literal breaks, resulting in the preservation of line formatting.</p> <p>To use this method, simply wrap the textarea in a <pre class="brush:php;toolbar:false"> container:</p> <div class="code" style="position:relative; padding:0px; margin:0px;"><pre class="brush:php;toolbar:false"><pre class="brush:php;toolbar:false"><textarea>This is a string</textarea>
This will ensure that line breaks entered within the textarea are displayed as intended in the output.
The above is the detailed content of How Can I Preserve Line Breaks from a Textarea in PHP Output?. For more information, please follow other related articles on the PHP Chinese website!