How can nl2br and htmlentities be combined in PHP to handle special characters and line breaks in user input?

When handling user input in PHP, it's important to escape special characters to prevent security vulnerabilities and display line breaks properly. To achieve this, you can combine the nl2br function to convert new lines to HTML line breaks and the htmlentities function to convert special characters to HTML entities. This ensures that user input is sanitized and displayed correctly on the webpage.

$userInput = $_POST['user_input']; // Assuming user input is received via POST method

// Sanitize user input
$sanitizedInput = nl2br(htmlentities($userInput));

echo $sanitizedInput; // Display sanitized user input