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:
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.
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.
<?php $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:
OUTPUT: Bringing<br /> Knowledge<br /> Together
Example 2: Getting Valid xhtml Output
Similarly, if you pass the second parameter as false, the function will generate valid xhtml markup.
<?php $string = "Bringing\nKnowledge\nTogether"; $finalString = nl2br($string, false); echo $finalString; ?>
Bringing<br> Knowledge<br> Together
Example 3: Using Various Newline Characters
Similarly, you can use the function for various newline characters as follows:
<?php $string = "This\r\nis\n\ra\nstring\r"; echo nl2br($string); ?>
OUTPUT: This<br /> is<br /> a<br /> string<br />
Vishesh is currently working as a Lead Software Engineer at Naukri.com. He passed out of Delhi College of Engineering in 2016 and likes to play Foosball. He loves traveling and is an exercise freak. His expertise includes Java, PHP, Python, Databases, Design and Architecture.