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, suggests the cursor to be moved to the next line and 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 languge HTML doesn’t understand the new line character sequence, this is where the Function finds its utilization.
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:
Hey There! Welcome.<br /> -GeeksforGeeks
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 whereas Linux uses and MAC uses .
- 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.