PHP nl2br Function | Insert Line Breaks Before Newlines

PHP nl2br is an inbuilt function in PHP. It inserts line breaks (<br/>) before every newline character in a string. The function supports the following newline characters:

  • \r
  • \n
  • \r\n
  • \n\r

In this article, we will discuss the PHP nl2br Function. Also, we will discuss a few examples of using it.


string nl2br ($string, $is_xhtml = true);


The PHP nl2br function expects two parameters. The description of the parameters is as follows:

  • $string: The input string to process in the function. Also, it is a mandatory parameter.
  • $is_xhtml: Whether to use XHTML compatible line breaks or not. However, it is an optional parameter with default value as true.

Return Value

The PHP nl2br function returns a string after inserting line breaks in front of all the newline characters. Also, it does not replace the line breaks, it inserts <br/> tag in front of all the existing line breaks.


Let’s discuss a few examples of using the function.

Example 1: Simple Usage

For instance, consider the following string as input to the function.

	$string = "Bringing\nKnowledge\nTogether";
	$finalString = nl2br($string);
	echo $finalString;


In the above example, the input string contains 2 newline characters. The function inserts line break tag (<br /> in front of the newline characters. The output of the function is as follows:

Bringing<br />
Knowledge<br />

Example 2: Getting Valid xhtml Output

Similarly, if you pass the second parameter as false, the function will generate valid xhtml markup.

	$string = "Bringing\nKnowledge\nTogether";
	$finalString = nl2br($string, false);
	echo $finalString;


Example 3: Using Various Newline Characters

Similarly, you can use the function for various newline characters as follows:

$string = "This\r\nis\n\ra\nstring\r";
echo nl2br($string);

This<br />
is<br />
a<br />
string<br />


In this article, we discussed the PHP nl2br function. You can read more about it on the Official PHP Documentation. Additionally, you can learn about more PHP String Functions on Concatly.

Spread the Knowledge

Leave a Reply

Your email address will not be published. Required fields are marked *