What are some common pitfalls when using regular expressions to extract data from a string in PHP?

One common pitfall when using regular expressions to extract data from a string in PHP is not properly escaping special characters. This can lead to unexpected results or errors when trying to match specific patterns in the string. To solve this issue, you can use the preg_quote() function to escape special characters before using them in your regular expression pattern.

// Incorrect way without escaping special characters
$string = "Hello, my email is john.doe@example.com";
$pattern = "/\b[a-zA-Z0-9._%+-]+@[a-zA-Z0-9.-]+\.[a-zA-Z]{2,}\b/";
preg_match($pattern, $string, $matches);
print_r($matches); // This may not return the expected email address

// Correct way with escaping special characters
$string = "Hello, my email is john.doe@example.com";
$escaped_pattern = "/\b" . preg_quote("[a-zA-Z0-9._%+-]+@[a-zA-Z0-9.-]+\.[a-zA-Z]{2,}", "/") . "\b/";
preg_match($escaped_pattern, $string, $matches);
print_r($matches); // This will correctly extract the email address