PHP nl2br() Function (original) (raw)

Last Updated : 21 Jun, 2023

The nl2br() is an inbuilt function in PHP and is used to insert HTML break tags in the place of all new lines in a string. In normal text editors, the new line is generally denoted by using any of the following.

Where, \n suggests the cursor to be moved to the next line and \r tells the cursor to be moved to the beginning of the line. This function takes strings that may contain newlines and returns an altered string by inserting br tag before all the new line character sequences. Being a markup language HTML doesn’t understand the new line character sequence, this is where the Function finds its utilization.

Syntax:

nl2br($str, $isXHTML)

Parameters: The function can take at most two parameters as follows.

Return Type: This function iterates over the input string and inserts br tag before each line break and returns the altered string.

Below programs illustrates the working of nl2br() in PHP:

<?php

$unaltered_string = "Hey There! Welcome.\n-GeeksforGeeks" ;

echo nl2br ( $unaltered_string );

?>

Output:

Hey There! Welcome.
-GeeksforGeeks

<?php

$unaltered_string = "I am a line.\r\nI am as well.\n\rSame here.\nMe too.\r" ;

echo nl2br ( $unaltered_string , false);

?>

Output:

I am a line.
I am as well.
Same here.
Me too.

Important points to note:

Reference: http://php.net/manual/en/function.nl2br.php