How to Convert Newlines to HTML Breaks with PHP’s nl2br Function

Learn how PHP's nl2br function inserts HTML line break tags before every newline in a string, understand its optional XHTML mode, see detailed parameter explanations, and explore three practical code examples demonstrating different newline scenarios and their resulting HTML output.

Laravel Tech Community
Laravel Tech Community
Laravel Tech Community
How to Convert Newlines to HTML Breaks with PHP’s nl2br Function

The nl2br function in PHP inserts an HTML line break tag ( <br /> or <br>) before each newline character in a given string and returns the modified string.

Parameters

string : The input string to be processed.

is_xhtml (optional, boolean): Determines whether to use XHTML‑compatible line breaks ( <br />) when set to true. The default is true.

Return value

The function returns the adjusted string with HTML break tags inserted.

Example 1

<?php
echo nl2br("foo isn't
 bar");
?>

Output:

foo isn't<br /> bar

Example 2

<?php
echo nl2br("Welcome
This is my HTML document", false);
?>

Output:

Welcome<br>This is my HTML document

Example 3

<?php
$string = "This
is
\ra
string\r";
echo nl2br($string);
?>

Output:

This<br />is<br />a<br />string<br />
Original Source

Signed-in readers can open the original source through BestHub's protected redirect.

Sign in to view source
Republication Notice

This article has been distilled and summarized from source material, then republished for learning and reference. If you believe it infringes your rights, please contactadmin@besthub.devand we will review it promptly.

BackendPHPStringHTMLfunctionnl2br
Laravel Tech Community
Written by

Laravel Tech Community

Specializing in Laravel development, we continuously publish fresh content and grow alongside the elegant, stable Laravel framework.

0 followers
Reader feedback

How this landed with the community

Sign in to like

Rate this article

Was this worth your time?

Sign in to rate
Discussion

0 Comments

Thoughtful readers leave field notes, pushback, and hard-won operational detail here.