What are some common mistakes to avoid when using preg_match() in PHP for input validation?

One common mistake to avoid when using preg_match() for input validation in PHP is not anchoring the regular expression properly. To ensure that the entire input string is validated against the pattern, you should use the ^ and $ anchors at the beginning and end of the regular expression, respectively. This prevents partial matches and ensures that the entire input meets the validation criteria.

// Incorrect way without proper anchoring
if (preg_match("/[0-9]{3}/", $input)) {
    // Validation passed
} else {
    // Validation failed
}

// Correct way with proper anchoring
if (preg_match("/^[0-9]{3}$/", $input)) {
    // Validation passed
} else {
    // Validation failed
}