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
Syntax
nl2br(string $string, bool $use_xhtml = true): string
Parameters
| Parameter | Description |
|---|---|
string |
The input string. |
use_xhtml optional |
true inserts <br />, false inserts <br>. Default: true |
Return value
The string with <br> tags added.
Examples
<?php
echo nl2br("Line one\nLine two"), "\n";
echo nl2br("A\nB", false), "\n";
Output
Line one<br /> Line two A<br> B
<?php
$comment = "<b>Hi</b>\nThanks!";
echo nl2br(htmlspecialchars($comment)), "\n";
Output
<b>Hi</b><br /> Thanks!
Version history
| Version | Change |
|---|---|
| PHP 4.0 | Added |
Related
htmlspecialchars()· Convert &, <, >, " and ' to HTML entities so user text is shown as text, not run as HTML. The main defence against XSS.wordwrap()· Wrap a string at a given line width by inserting line breaks between words, optionally cutting long words.- PHP Strings · tutorial
- PHP Form Handling · tutorial