What are some best practices for efficiently extracting email addresses from a string in PHP?

When extracting email addresses from a string in PHP, one efficient approach is to use regular expressions to match email patterns within the string. By using the preg_match_all function with a regex pattern, you can extract all email addresses present in the string. Additionally, it's important to sanitize and validate the extracted email addresses to ensure they are valid before further processing.

$string = "Lorem ipsum dolor sit amet, consectetur adipiscing elit. Email addresses: john.doe@example.com, jane.smith@example.com";

$pattern = '/\b[A-Za-z0-9._%+-]+@[A-Za-z0-9.-]+\.[A-Z|a-z]{2,}\b/';
preg_match_all($pattern, $string, $matches);

$emails = $matches[0];
print_r($emails);