How to Use nl2br in PHP: Convert Newlines to HTML Breaks
Use the
nl2br() function in PHP to convert newline characters (\n) in a string into HTML <br> tags. This helps display text with line breaks correctly in a web browser.Syntax
The nl2br() function takes a string and returns it with newline characters replaced by HTML <br> tags. It has one required parameter and one optional parameter.
- string: The input text containing newlines.
- is_xhtml (optional): If
true, inserts<br />(XHTML style). Default istrue.
php
string nl2br(string $string, bool $is_xhtml = true)Example
This example shows how nl2br() converts newlines in a string to HTML line breaks so the text displays with line breaks in a browser.
php
<?php
$text = "Hello\nWorld!\nWelcome to PHP.";
echo nl2br($text);
?>Output
Hello<br />
World!<br />
Welcome to PHP.
Common Pitfalls
One common mistake is forgetting that nl2br() only affects how newlines are displayed in HTML, not in plain text output. Also, if you echo the string without nl2br(), newlines won't create visible breaks in HTML.
Another pitfall is misunderstanding the is_xhtml parameter: setting it to false outputs <br> instead of <br />.
php
<?php // Wrong: newlines won't show as breaks in HTML echo "Line 1\nLine 2"; // Right: use nl2br to convert newlines to <br> echo nl2br("Line 1\nLine 2"); // Using is_xhtml = false outputs <br> instead of <br /> echo nl2br("Line 1\nLine 2", false); ?>
Output
Line 1
Line 2Line 1<br />
Line 2Line 1<br>
Line 2
Quick Reference
- nl2br(string $string, bool $is_xhtml = true): Converts newlines to HTML line breaks.
- Default inserts
<br />tags for XHTML compliance. - Set
$is_xhtmltofalsefor HTML5 style<br>tags. - Use when displaying plain text with newlines in HTML.
Key Takeaways
Use nl2br() to convert newline characters to HTML
tags for proper line breaks in web pages.
tags for proper line breaks in web pages.
By default, nl2br() inserts XHTML-style
tags; set the second parameter to false for HTML5 style
tags.
tags; set the second parameter to false for HTML5 style
tags.
nl2br() only affects HTML output; newlines in plain text need this function to show as line breaks in browsers.
Remember to echo or print the result of nl2br() to see the converted output.
Avoid using nl2br() on already escaped HTML to prevent unwanted tags.