PHP nl2br() Function
Last Updated :
21 Jun, 2023
Improve
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.
PHP
Output:
PHP
Output:
- \n\r
- \r\n
- \n
- \r
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.
<?php
// PHP code to illustrate the working of nl2br()
$unaltered_string = "Hey There! Welcome.\n-GeeksforGeeks";
echo nl2br($unaltered_string);
?>
Hey There! Welcome.<br /> -GeeksforGeeks
<?php
// 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.