How can special characters and letters be properly handled when using PHP functions for input validation?

Special characters and letters can be properly handled in PHP input validation by using functions like htmlspecialchars() to sanitize user input and prevent cross-site scripting attacks. Additionally, using regular expressions with functions like preg_match() can help validate specific patterns of characters in input.

// Sanitize user input using htmlspecialchars
$user_input = "<script>alert('XSS attack');</script>";
$sanitized_input = htmlspecialchars($user_input, ENT_QUOTES);

// Validate input using regular expressions
if (preg_match("/^[a-zA-Z0-9]+$/", $user_input)) {
    echo "Input is valid.";
} else {
    echo "Invalid input.";
}