nl2br
Inserts a br tag before every line break.
Syntax
nl2br(string $string): stringParameters
| Parameter | Type | Description |
|---|---|---|
| $string | string | The source text. |
Return value
stringThe text with `<br />` tags.
Examples
Text from a multi-line field:
<?php
echo nl2br("First line\nSecond line");Output:
First line<br />
Second lineEscape first, then add the breaks:
<?php
$comment = "<b>Hi</b>\nBye";
echo nl2br(htmlspecialchars($comment));Output:
<b>Hi</b><br />
ByeNotes
A browser does not show line breaks in HTML. Call nl2br() after htmlspecialchars(), otherwise the added tags get escaped too.
See also
- htmlspecialchars — Replaces HTML special characters with safe entities.
- str_replace — Replaces all occurrences of a substring with another string.
Related recipes
In the tutorial
- Forms and request data — Handling forms in PHP — the $_GET and $_POST arrays, validating data and preventing XSS with htmlspecialchars.