PHP 8 reference · String Functions

PHP nl2br() Function

Insert an HTML <br> tag before every new line in a string, so plain text keeps its line breaks on a web page.

PHP 8 Since 4.0

Create a free account to save this page, take notes and track your progress. Sign in

Syntax

nl2br(string $string, bool $use_xhtml = true): string

Parameters

ParameterDescription
string The input string.
use_xhtml optional true inserts <br />, false inserts <br>. Default: true

Return value

The string with <br> tags added.

Examples

Keep line breaks in HTMLTry it yourself
<?php
echo nl2br("Line one\nLine two"), "\n";
echo nl2br("A\nB", false), "\n";

Output

Line one<br />
Line two
A<br>
B
Escape first, then add breaksTry it yourself
<?php
$comment = "<b>Hi</b>\nThanks!";
echo nl2br(htmlspecialchars($comment)), "\n";

Output

&lt;b&gt;Hi&lt;/b&gt;<br />
Thanks!

Version history

VersionChange
PHP 4.0Added

Was this page helpful?