What are common pitfalls to avoid when working with nl2br in PHP for text formatting?

One common pitfall when working with nl2br in PHP is forgetting to escape HTML entities before applying nl2br to prevent potential XSS attacks. To avoid this issue, always use htmlspecialchars() before using nl2br on user-generated content.

$userInput = "<script>alert('XSS attack');</script>\nNew line";
$escapedInput = htmlspecialchars($userInput);
$formattedText = nl2br($escapedInput);

echo $formattedText;