How to Use nl2br() Function in PHP 8.1 and 8.2 with Example?

Support PHP Version: PHP 7.1, PHP 7.2, PHP 7.3, PHP 7.4, PHP 8.0, PHP 8.1, PHP 8.2, PHP 8.3 With Latest All Version Support.

In PHP, the `nl2br()` function is used to insert HTML line breaks (`<br>`) before all newlines in a string. This function is particularly useful when dealing with text that contains line breaks and you want to display it in HTML while preserving those line breaks. In PHP 8.1 and 8.2, the `nl2br()` function works the same way as in previous versions.

Here’s how you can use the `nl2br()` function with an example:

// Example string containing newlines
$text = "This is a sample text.\nWith new lines.\nAnd another line.";
// Applying nl2br() function
$formattedText = nl2br($text);
// Displaying the formatted text
echo $formattedText;


This is a sample text.<br>With new lines.<br>And another line.

In this example, the `nl2br()` function replaces each newline character (`\n`) in the original string with the HTML `<br>` tag, resulting in line breaks in the output when displayed in an HTML context.

Remember that when using `nl2br()`, it’s important to keep in mind potential security risks, especially if the input contains user-generated content. You may want to sanitize or validate the input to prevent malicious HTML or script injection.