Tutorialspoint.dev

PHP | nl2br() Function

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.

Syntax:

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

/div>

Output:

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. I am as well. Same here. Me too. ";
echo nl2br($unaltered_string, false);
  
?>

Output:

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.

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



This article is attributed to GeeksforGeeks.org

You Might Also Like

leave a comment

code

0 Comments

load comments

Subscribe to Our Newsletter