What are common pitfalls when using preg_match to validate input in PHP?
Common pitfalls when using preg_match to validate input in PHP include not properly escaping special characters in the regular expression, not anchoring the pattern to match the entire input, and not handling edge cases or variations in input format. To solve these issues, always use the \ to escape special characters, use ^ and $ to anchor the pattern, and consider all possible input variations.
// Example of properly escaping special characters and anchoring the pattern
$input = "example123";
if (preg_match("/^[a-zA-Z0-9]+$/", $input)) {
echo "Input is valid.";
} else {
echo "Input is invalid.";
}