What are the potential pitfalls of using nl2br() function in PHP for handling special characters?

The potential pitfall of using nl2br() function in PHP for handling special characters is that it can inadvertently convert special characters into HTML entities, which may not be the desired behavior. To solve this issue, we can use htmlspecialchars() function to first escape the special characters before using nl2br().

$text = "<p>This is a <b>bold</b> statement.</p>";
$escaped_text = htmlspecialchars($text);
$final_text = nl2br($escaped_text);

echo $final_text;