How can the order of functions like htmlentities() and preg_match() affect the outcome of input validation in PHP?

The order of functions like htmlentities() and preg_match() can affect the outcome of input validation in PHP because htmlentities() should be applied after preg_match() to ensure that special characters are properly encoded. If htmlentities() is applied before preg_match(), it may alter the input in a way that interferes with the pattern matching process. To solve this issue, always perform preg_match() first to validate the input, and then apply htmlentities() to encode special characters.

$input = $_POST['input'];

// Validate input using preg_match()
if(preg_match('/^[a-zA-Z0-9\s]+$/', $input)){
    // Input is valid, now encode special characters using htmlentities()
    $safe_input = htmlentities($input);
} else {
    echo "Invalid input!";
}