Skip to content
Tutorials Center
My learning

Topics

PHP Reference ยท String Functions

PHP nl2br() function

Reference for PHP nl2br(): insert HTML line breaks before newlines, XHTML versus HTML output, and why you must escape user text with htmlspecialchars() first.

nl2br() inserts an HTML line break tag before every newline in a string. Browsers collapse newlines in HTML, so text typed into a <textarea> loses its line structure unless you convert it.

The original newline is kept; the tag is added in front of it. By default the tag is <br />; pass false as the second argument to get <br>.

PHP
<?php
echo nl2br("one\ntwo");

Try it

PHP Newlines to line breaks

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with fgets(STDIN)), it gets the next line from this box.

PHP Escape first, then convert

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with fgets(STDIN)), it gets the next line from this box.

Syntax

PHP
nl2br(string $string, bool $use_xhtml = true): string
Name Description
$string The input string.
$use_xhtml If true (default) the inserted tag is <br />; if false it is <br>.

Return value: the string with a break tag inserted before each newline.

Usage notes

  • Recognized newlines: \n, \r, \r\n and \n\r. A pair such as \r\n counts as one line break.
  • The newline stays. The result still contains the original newline characters after each tag, which is harmless in HTML.
  • It does not escape anything. Always run user input through htmlspecialchars() first, as in the second example, or you create a cross-site scripting hole.
  • Alternatives: the CSS rule white-space: pre-line shows newlines without changing the data, which keeps the stored text clean.
  • Opposite direction: there is no built-in br2nl; use preg_replace('/<br\s*\/?>/i', "\n", $html).
  • Console and email text do not need it; use the platform's own line endings (see PHP_EOL and line endings).