Home > Backend Development > PHP Tutorial > How Can I Preserve Line Breaks from a Textarea in PHP Output?

How Can I Preserve Line Breaks from a Textarea in PHP Output?

DDD
Release: 2024-12-05 02:34:09
Original
962 people have browsed it

How Can I Preserve Line Breaks from a Textarea in PHP Output?

Preserving Line Breaks in TextArea Output

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);
?>
Copy after login

This code will output:

This<br />
is<br />
a<br />
string<br />
Copy after login

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>
Copy after login

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!

source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Popular Recommendations
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template