Location via proxy:   [ UP ]  
[Report a bug]   [Manage cookies]                

PHP String nl2br() Function



The PHP String nl2br() function is used to replace all new lines in a string with HTML break tags. Any of the following is typically used in standard text editors to indicate the new line.

  • \n\r

  • \r\n

  • \n

  • \r

Where, \r tells the cursor to be moved to the start of the line, and \n says that it should be moved to the next line. This function inserts a br tag before each new line character sequence in strings that may include newlines, returning a modified string. The function is used because HTML, being a markup language, is unable to comprehend the new line character sequence.

Syntax

Below is the syntax of the PHP String nl2br() function −

string nl2br ( string $string [, bool $is_xhtml = true ] )

Parameters

Here are the parameters of the nl2br() function −

  • $string − It contains the information about input string.

  • $is_xhtml − It contains the information about whether to use XHTML compatible line breaks or not.

Return Value

The nl2br() function returns the altered string.

PHP Version

First introduced in core PHP 4, the nl2br() function continues to function easily in PHP 5, PHP 7, and PHP 8.

Example 1

Here is the first example to show you the usage of the PHP String nl2br() function.

<?php
   echo nl2br("Tutorialspoint.\nAnother line.");
?>

Output

Here is the outcome of the following code −

Tutorialspoint.<br /<
Another line.

Example 2

In the below PHP code we will use the nl2br() function and replace newlines with <br> tags in a string.

<?php
   // Input string 
   $text = "Hello\nWorld\nThis is PHP";

   // Using nl2br to convert newlines 
   $result = nl2br($text);

   // Display the result
   echo $result;
?> 

Output

This will generate the below output −

Hello<br />
World<br />
This is PHP 

Example 3

In this example, we will show how to handle different newline sequences (\r\n, \n, \r) in a string using the nl2br() function.

<?php
   // Input string with different newline characters
   $text = "Line1\r\nLine2\nLine3\rLine4";

   // Using nl2br
   $result = nl2br($text);

   // Display the result
   echo $result;
?> 

Output

This will create the below output −

Line1<br />
Line2<br />
Line3<br />
Line4 
php_function_reference.htm
Advertisements