PHP Function Reference

PHP nl2br() Function



The PHP nl2br() function returns string with <br /> or <br> inserted before all newlines (\r\n, \n\r, \n and \r).

Syntax

nl2br(string, use_xhtml)

Parameters

string Required. Specify the input string.
use_xhtml Optional. Specify whether to use XHTML compatible line breaks or not. Default is true.

Return Value

Returns the converted string.

Example:

The example below shows the usage of nl2br() function.

<?php
$str = "The quick brown \nfox jumped over \r\nthe lazy dog.";
$converted_str = nl2br($str);

//displaying the converted string
echo $converted_str;
?>

The output of the above code will be:

The quick brown <br />
fox jumped over <br />
the lazy dog.

Example: Generating valid HTML markup

Consider one more example where the use_xhtml parameter is used to control the XHTML compatible line breaks.

<?php
$str = "The quick brown \nfox jumped over \r\nthe lazy dog.";

$converted_str1 = nl2br($str);
$converted_str2 = nl2br($str, false);

//displaying the converted string
echo $converted_str1;
echo "\n\n";
echo $converted_str2;
?>

The output of the above code will be:

The quick brown <br />
fox jumped over <br />
the lazy dog.

The quick brown <br>
fox jumped over <br>
the lazy dog.

❮ PHP String Reference