Extract Email Addresses From a String – PHP

Sometimes you need to extract multiple email addresses from a string and the following function will make all your dreams come true.

function extract_emails_from($string){
    preg_match_all("/[\._a-zA-Z0-9-]+@[\._a-zA-Z0-9-]+/i", $string, $matches);
    return $matches[0];
}

..and this is how you use it:

$text = "this is some text and here is an email address [email protected], here's another [email protected], etc..";
$emails = extract_emails_from($text);

Now let’s use the data:

// as string
print(implode("\n", $emails));

// loop as array
foreach($emails as $email) {
    echo $email .",";
}