PHP nl2br() Function with Example

By IncludeHelp Last updated : December 27, 2023

PHP nl2br() function

The nl2br() stands for "New Line to Break", this function converts all new line characters (\n) to break tag (<br>) in the string. It can be seen by viewing the source of the HTML.

Syntax

The syntax of the nl2br() function:

nl2br(string, [xhtml]);

Parameters

The parameters of the nl2br() function:

  • string: An input parameter (string).
  • xhtml: It is an optional parameter and it is used to either use <br> - if xhtml value is FALSE, or use <br /> - if xhtml value is TRUE. If you don't use this parameter, the default value will be TRUE.

Return Value

The return value of this method is string, it converts and returns the string with <br> tag instead of all \n (New line character).

Sample Input/Output

Input:
"Hello\nWorld"

Output:
Hello<br />
World

Example of PHP nl2br() Function

<?php
$str = "Hello\nWorld\n";
echo nl2br($str);

$str = "My\nName\nis\nIncludeHelp\n";
echo nl2br($str);

$str = "Hello\nWorld\n";
echo nl2br($str,FALSE);

$str = "My\nName\nis\nIncludeHelp\n";
echo nl2br($str,FALSE);    
?>

Output

The output of the above example is:

Hello<br />
World<br />
My<br />
Name<br />
is<br />
IncludeHelp<br />
Hello<br>
World<br>
My<br>
Name<br>
is<br>
IncludeHelp<br>

To understand the above example, you should have the basic knowledge of the following PHP topics:

All PHP Programs

Comments and Discussions!

Load comments ↻





Copyright © 2024 www.includehelp.com. All rights reserved.