PHP nl2br() Function

Example

Insert a newline (\n) before a new line in the string:

<?php
echo nl2br("One line.\nAnother line.");
?>

Browser Output of the above code:

One line.
Another line.

HTML Input of the above code (View Source Code):

One line.<br />
Another line.

Run Instance

Definition and Usage

The nl2br() function inserts an HTML line break (<br> or <br />) before each new line (\n) in the string.

Syntax

nl2br(string,xhtml)
Parameter Description
string Required. Specifies the string to be checked.
xhtml

Optional. Boolean value indicating whether to use compatible XHTML line breaks:

  • TRUE - Default. Inserts <br />
  • FALSE - Inserts <br>

Technical Details

Return Value: Returns the converted string.
PHP Version: 4+
Update Log:

Before PHP 4.0.5, the function inserts <br>. After PHP 4.0.5, the function inserts <br /> compatible with XHTML.

Added in PHP 5.3 xhtml Parameter.

More Examples

Example 1

By using xhtml Parameters, insert a newline (\n) before (in new line):

<?php
echo nl2br("One line.\nAnother line.",false);
?>

Browser Output of the above code:

One line.
Another line.

HTML Input of the above code (View Source Code):

One line.<br>
Another line.

Run Instance