Search code snippets, questions, articles...

nl2br() function in PHP

The nl2br() function in PHP is used to convert newline characters to HTML line break tags. This function is useful for preserving the line breaks in the text when displaying it in a web browser. The nl2br() function inserts HTML line breaks (br) before all newlines in a string.
<?php
   echo nl2br("First line.\nSecond line.\nThird Line");
?>
Best JSON Validator, JSON Tree Viewer, JSON Beautifier at same place.

nl2br function in PHP

The nl2br() function in PHP is used to convert newlines to HTML line breaks (<br>). This is useful when displaying text in a web browser because new lines will not be visible unless they are converted to line breaks.

The nl2br() function is especially useful when displaying text that has been entered by a user because it ensures that the text will be displayed correctly in the web browser.

Syntax

nl2br(String)

Code example

<?php
   $str = "Text 1.\nText 2.\nText 3.";
   echo nl2br($str);
?>

Output

Text 1.<br />
Text 2.<br />
Text 3.

In the above code example, we have a string called $str that contains multiple line breaks. We are passing this string to the nl2br() function that will replace the \n with <br> HTML tags.


Replace all \n with <br> tags

If you want to display some text on a web page, you might want to use line breaks to make the text more readable. However, HTML will not recognize line breaks unless you use the <br> tag.

You can use the nl2br() function to automatically replace all line breaks with <br> tags.

Was this helpful?
0 Comments