Extract E-Mails

This function extracts all E-Mail adresses from a given string, and returns them as array.

Snippet information

Author:
Jonas John

License:
Public Domain

Language:
PHP

Created:
05/19/2006

Updated:
05/19/2006

Tags:
,


function extract_emails($str){
    // This regular expression extracts all emails from
    // a string:
    $regexp = '/([a-z0-9_\.\-])+\@(([a-z0-9\-])+\.)+([a-z0-9]{2,4})+/i';
    preg_match_all($regexp, $str, $m);
 
    return isset($m[0]) ? $m[0] : array();   
}
 
$test_string = 'This is a test string...
 
        test1@example.org
 
 
        Test different formats:    
        test2@example.org;
        <a href="test3@example.org">foobar</a>
        <test4@example.org>
 
 
        strange formats:        
        test5@example.org
        test6[at]example.org
        test7@example.net.org.com
        test8@ example.org
        test9@!foo!.org
 
        foobar   
';
 
print_r(extract_emails($test_string));
 
/*
 
    Returns this array:
 
    Array
    (
        [0] => test1@example.org
        [1] => test2@example.org
        [2] => test3@example.org
        [3] => test4@example.org
        [4] => test5@example.org
        [5] => test7@example.net.org.com
    )
 
*/


Found a bug? Or do you have a better solution for this?
Feel free to leave a message:

Add a comment


Leave a comment

asdfasdf September 25, 2009 at 10:11
asldfjasf
Johnny Backlink September 04, 2009 at 23:21
So, this is the guy...