PHP nl2br()Functions
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.
Another line.
The HTML input of the above code is as follows (view source):
One line.<br />
Another line.
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:
|
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:
echo nl2br("One line.\nAnother line.",false);
The browser output of the above code is as follows:
One line.
Another line.
Another line.
The HTML input of the above code is as follows (view source):
One line.<br>
Another line.
Another line.
Run example »
PHP String Reference Manual Other Extensions