What is the purpose of using preg_match_all() function in PHP?

The preg_match_all() function in PHP is used to perform a global regular expression match on a string and return all matches. This function is useful when you need to find multiple occurrences of a pattern within a string and extract them for further processing. It returns an integer representing the number of full pattern matches found, or false if an error occurs.

// Example of using preg_match_all() to extract all email addresses from a string
$string = "John's email is john@example.com and Jane's email is jane@example.com";
$pattern = '/\b[A-Za-z0-9._%+-]+@[A-Za-z0-9.-]+\.[A-Z|a-z]{2,}\b/';
preg_match_all($pattern, $string, $matches);

print_r($matches[0]);