Open In App

PHP nl2br() Function

Last Updated : 21 Jun, 2023
Like Article

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.

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

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.


nl2br($str, $isXHTML)

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

  • $str: The string to be altered.
  • $isXHTML: This is an optional parameter and expects a boolean value to denote whether to use XHTML compatible line breaks or not i.e. whether to use <br /> or not. Default value is true.

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 code to illustrate the working of nl2br()
$unaltered_string = "Hey There! Welcome.\n-GeeksforGeeks";
echo nl2br($unaltered_string);


Hey There! Welcome.<br />

// PHP code to illustrate the working of nl2br() 
// with optional parameter isXHTML
// and every new line sequence.
$unaltered_string = "I am a line.\r\nI am as well.\n\rSame here.\nMe too.\r";
echo nl2br($unaltered_string, false);


I am a line.<br>
I am as well.<br>
Same here.<br>
Me too.<br>

Important points to note:

  • It is used to display text stored in databases.
  • Different Operating System prefer to use different character sequences as line breaks such as Windows uses \r\n whereas Linux uses \n and MAC uses \r.
  • Similar result can be produced using simple string replacement, though it is to be remembered that the nl2br function doesn’t replace the new line sequences.


Like Article
Suggest improvement
Share your thoughts in the comments

Similar Reads