Home > Backend Development > PHP Tutorial > How to Preserve Line Breaks from Textarea Input in PHP and HTML?

How to Preserve Line Breaks from Textarea Input in PHP and HTML?

Patricia Arquette
Release: 2024-12-05 03:50:10
Original
753 people have browsed it

How to Preserve Line Breaks from Textarea Input in PHP and HTML?

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

Output:

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

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/pre

The 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!

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