Home > Database > Mysql Tutorial > How Can I Preserve Line Breaks in Textarea Input?

How Can I Preserve Line Breaks in Textarea Input?

DDD
Release: 2024-12-30 11:07:09
Original
545 people have browsed it

How Can I Preserve Line Breaks in Textarea Input?

Preserve Line Breaks from TextArea

When allowing users to input comments via a textarea, it can be frustrating when new lines entered are removed from the output. This article addresses this issue and provides two solutions to ensure line breaks are preserved.

Solution 1: PHP nl2br() Function

The PHP nl2br() function converts new line characters (n) to HTML line breaks (
).

$input = "This\r\nis\n\ra\nstring\r";
echo nl2br($input);
Copy after login

Output:

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

Solution 2: HTML Preformatted Text

Enclosing the user's input within

 tags prevents browsers from altering its formatting. This includes preserving line breaks.

<pre class="brush:php;toolbar:false">
This
is
a
string
Copy after login

Output:

This
is
a
string
Copy after login

The above is the detailed content of How Can I Preserve Line Breaks in Textarea Input?. For more information, please follow other related articles on the PHP Chinese website!

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 Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template