What are the potential pitfalls of using nl2br function in PHP for formatting text?

The nl2br function in PHP can potentially introduce security vulnerabilities such as Cross-Site Scripting (XSS) attacks if user input is not properly sanitized. To prevent this, it is important to use htmlspecialchars function to escape HTML entities before using nl2br to convert newlines to <br> tags.

$text = &quot;&lt;script&gt;alert(&#039;XSS attack!&#039;);&lt;/script&gt;\nThis is a new line.&quot;;
$safe_text = htmlspecialchars($text);
$formatted_text = nl2br($safe_text);

echo $formatted_text;