What are common pitfalls when using preg_match in PHP for data filtering?

One common pitfall when using preg_match in PHP for data filtering is not properly escaping special characters in the regular expression pattern, which can lead to unexpected results or vulnerabilities. To avoid this, it is important to use the preg_quote function to escape any special characters in the pattern before using it in preg_match.

// Incorrect usage of preg_match without escaping special characters
$pattern = '/[a-z]+/';
$string = 'Hello, World!';
if (preg_match($pattern, $string)) {
    echo 'Match found!';
} else {
    echo 'No match found!';
}

// Corrected code with escaping special characters using preg_quote
$pattern = '/'.preg_quote('[a-z]+').'/';
$string = 'Hello, World!';
if (preg_match($pattern, $string)) {
    echo 'Match found!';
} else {
    echo 'No match found!';
}