PHP nl2br() Function
PHP nl2br() Syntax
nl2br(string $string, bool $use_xhtml = true): string
PHP nl2br() Basic examples
$text = "Line 1\nLine 2";
echo nl2br($text);
Line 1<br />
Line 2
Converts newline characters to HTML line breaks.
PHP nl2br() Real-world usage
$comment = "Hello\nWorld";
echo nl2br(htmlspecialchars($comment));
Hello<br />
World
Safely displays user-entered text with line breaks.
PHP nl2br() Edge cases
$text = "Single line";
echo nl2br($text);
Single line
Strings without newlines are unchanged.
PHP nl2br() Common mistakes
Applying nl2br before escaping HTML
This can allow HTML injection.
echo nl2br($_POST['comment']);
echo nl2br(htmlspecialchars($_POST['comment']));
Always escape HTML before inserting <br> tags.
PHP nl2br() Frequently Asked Questions
What does nl2br() do in PHP?
nl2br() inserts HTML line breaks before all newline characters in a string.
What HTML tag does nl2br() use?
It inserts <br> or <br /> tags depending on the XHTML setting.
Does nl2br() modify the original string?
No, nl2br() returns a new string and does not modify the original variable.
What newline characters does nl2br() detect?
It detects \n, \r\n, \r, and \n\r newline sequences.
Can nl2br() be used with HTML safely?
Yes, but combine it with htmlspecialchars() to prevent XSS.
Does nl2br() escape HTML?
No, nl2br() does not escape HTML content.
What is the second parameter in nl2br()?
The second parameter controls whether to use XHTML-compatible <br /> tags.
Is nl2br() safe for user input?
Only when combined with proper escaping like htmlspecialchars().
Can nl2br() handle empty strings?
Yes, it returns an empty string when input is empty.
Does nl2br() remove newlines?
No, it adds <br> tags but keeps the original newline characters.
What is a real-world use case of nl2br()?
It is used to display user-entered text with preserved line breaks in HTML.
Can nl2br() be reversed?
No direct reverse function exists; you need to remove <br> tags manually if needed.