What potential issues or pitfalls should be considered when combining nl2br and htmlentities in PHP for user input processing?

One potential issue when combining nl2br and htmlentities in PHP for user input processing is that applying htmlentities before nl2br can result in the line breaks being converted to HTML entities, making them ineffective. To solve this, it's important to apply nl2br first to preserve the line breaks, and then apply htmlentities to escape any HTML characters.

// Process user input with nl2br followed by htmlentities
$userInput = nl2br($_POST['user_input']);
$userInput = htmlentities($userInput);