How can PHP functions like htmlspecialchars() and strip_tags() be used properly in combination to clean text input?

When handling user input in PHP, it is crucial to sanitize the data to prevent security vulnerabilities like cross-site scripting (XSS) attacks. The htmlspecialchars() function converts special characters to HTML entities, making it safe to display user input on a webpage. The strip_tags() function, on the other hand, removes any HTML or PHP tags from the input, ensuring that only plain text remains. By using these functions in combination, you can effectively clean text input before processing or displaying it.

$userInput = "<script>alert('XSS attack!')</script>";
$cleanInput = strip_tags(htmlspecialchars($userInput));

echo $cleanInput;