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.
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 /> barExample 2
<?php
echo nl2br("Welcome
This is my HTML document", false);
?>Output:
Welcome<br>This is my HTML documentExample 3
<?php
$string = "This
is
\ra
string\r";
echo nl2br($string);
?>Output:
This<br />is<br />a<br />string<br />Signed-in readers can open the original source through BestHub's protected redirect.
This article has been distilled and summarized from source material, then republished for learning and reference. If you believe it infringes your rights, please contactand we will review it promptly.
Laravel Tech Community
Specializing in Laravel development, we continuously publish fresh content and grow alongside the elegant, stable Laravel framework.
How this landed with the community
Was this worth your time?
0 Comments
Thoughtful readers leave field notes, pushback, and hard-won operational detail here.
