PHP nl2br() Function

What is PHP nl2br() Function?

If you want to insert HTML line break (<br> or <br />) before all the newlines characters (\n, \r, \r\n, \n\r) in a string, use PHP nl2br() function.

HTML generally can’t understand newline characters and ignores those. So, everything displays in a line.  The nl2br() function helps text to display properly in the browser with line break.

Syntax:

nl2br(string, is_xhtml)

Parameters:

The function has 1 required parameter and 1 optional parameter-

string (Required): It specifies a string that the function processes.

is_xhtml (Optional): It specifies a Boolean value that indicates whether to use an XHTML or HTML line break-

  • TRUE – if it is TRUE, the function add an XHTML line break – <br />. It is the default value.
  • FALSE – if it is FALSE, the function add an HTML line break – <br>.

Return Values:

The function returns the modified string.

Examples:

Example 1:

<?php
echo nl2br("From \"Schools of Web\", learn web development-\nHTML\nCSS\nJavaScript\nREACT\nPHP\nMySQL");
?>

Output:

From "Schools of Web", learn web development-
HTML
CSS
JavaScript
REACT
PHP
MySQL

Example 2:

<?php
echo nl2br("From \"Schools of Web\", learn-\nWeb Development\nWeb Designing", FALSE);
?>

Output:

From "Schools of Web", learn-
Web Development
Web Designing

Practical uses of nl2br() Function:

  • The function is useful to display user data (ex. comment) properly in the browser.
  • It is also helpful to display data from database with line break.

Notes on nl2br() Function:

  • This function doesn’t replace the newlines, instead, it just add the line break tag (<br>) in front of a newline.
  • The function can detect all types of newline characters – for Windows(\r\n), for LINUX (]n), for MAC (\r).

PHP Version Support:

PHP 4, PHP 5, PHP 7, PHP 8

Summary: PHP nl2br() Function

nl2br() function is one of the built-in string functions. Use this function to display line break properly in a web browser.

Reference:

https://www.php.net/manual/en/function.nl2br.php