PHP nl2br() Function

Examples

Insert a newline (\n) before a new line in a 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 Instances

Definition and Usage

The nl2br() function inserts HTML line breaks (<br> or <br />) before each new line (\n) in a 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 (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 Instances