Encodera

Thanks for reading!

Donate to the site — we work hard for you.

PHP reference

nl2br

Inserts a br tag before every line break.

Syntax

nl2br(string $string): string

Parameters

ParameterTypeDescription
$stringstringThe 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 line

Escape first, then add the breaks:

<?php
 
$comment = "<b>Hi</b>\nBye";
 
echo nl2br(htmlspecialchars($comment));

Output:

&lt;b&gt;Hi&lt;/b&gt;<br />
Bye

Notes

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.

Thanks for reading!

Donate to the site — we work hard for you.