PHP nl2br()Functions

PHP String 参考手册PHP String Reference Manual

Examples

Insert line breaks before newlines (\n) in a string:

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

The browser output of the above code is as follows:

One line.
Another line.

The HTML input of the above code is as follows (view source):

One line.<br />
Another line.

Run example »

Definition and Usage

The nl2br() function inserts HTML line breaks (<br> or <br />) before each newline (\n) in a string.


Syntax

nl2br(string,xhtml)

Parameters Description
string Required. Specifies the string to be checked.
xhtml Optional. A Boolean value indicating whether to use XHTML-compatible line breaks:
  • TRUE - Default. Inserts <br />
  • FALSE - Inserts <br>

Technical Details

Return value: Returns the converted string.
PHP Version: 4+
Changelog: Before PHP 4.0.5, this function inserted <br>. After PHP 4.0.5, this function inserts XHTML-compatible <br />.

In PHP 5.3, thexhtmlparameter was added.


More Examples

Example 1

Insert line breaks before newlines (\n) by using the xhtml parameter:

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

The browser output of the above code is as follows:

One line.
Another line.

The HTML input of the above code is as follows (view source):

One line.<br>
Another line.

Run example »


PHP String 参考手册PHP String Reference Manual Other Extensions