PHP Function to Extract an E-mail from a String Programming 31 MAR 2013

kung-fu-php-logoGiven a string, it would often be quite useful to extract any e-mail addresses that it might contain. Luckily for us, PHP makes this fairly trivial through the use of its powerful filter_var functionality.

Essentially the plan of attack is to take the string, tokenize it by breaking it up on the space character (or whatever other delimiters you wish to use), and then loop through each one of those tokens and check if it matches a recognised email address pattern.

Putting all of this together, we would get a function which looks a little like this:

function email_address_extraction($message){
    foreach(preg_split('/ /', $message) as $token) {
        $email = filter_var(filter_var($token, FILTER_SANITIZE_EMAIL), FILTER_VALIDATE_EMAIL);
        if ($email !== false) {
            $emails[] = $email;
        }
    }
    return $emails;
}

To test:

$testmessage = "hello world.  can jon.kabal@image.com, craig.lot+blog@google.com, and roar@hype.com come over   and play?";
$result = email_address_extraction($testmessage);
print_r($result);
$testmessage = " craiglot@doe.co.za";
$result = email_address_extraction($testmessage);
print_r($result);

Nifty.

Related Posts:

About Craig Lotter

Software developer, husband and dad to two little girls. Writer behind An Exploring South African. I don't have time for myself any more.