What is the purpose of using preg_match_all in PHP and what are the potential pitfalls when using it?
The purpose of using preg_match_all in PHP is to perform a global search on a string using a regular expression, and return all matches found. When using preg_match_all, it is important to be cautious of potential pitfalls such as incorrect regular expressions leading to unexpected results, inefficient patterns causing performance issues, and the need to properly handle the returned matches to avoid errors.
// Example code snippet demonstrating the use of preg_match_all
$string = "The quick brown fox jumps over the lazy dog";
$pattern = '/\b\w{4}\b/'; // Match words with exactly 4 characters
if (preg_match_all($pattern, $string, $matches)) {
// Display all matches found
print_r($matches[0]);
} else {
echo "No matches found.";
}