nl2br() Function in PHP 8.5

What it does?

nl2br() inserts HTML <br> (or <br />) tags before every newline character ( , , ) in a string. It does not remove the newline — it adds a line break tag before it. Useful for displaying user-submitted text (e.g., from textareas) in HTML while preserving line breaks.

Signature

nl2br(string $string, bool $use_xhtml = true): string

  • $string — the input string.
  • $use_xhtml — if true (default), inserts <br />; if false, inserts <br>.

Returns the modified string.

Basic example

<?php

$text = "Hello World. This is PHP. Enjoy coding!";

echo nl2br($text); 

?>

Output (HTML source):

Hello World.<br />

This is PHP.<br />

Enjoy coding!

In the browser this renders as three lines.

5 Views