Skip to content

Instantly share code, notes, and snippets.

@vrushank-snippets
Created March 23, 2012 10:59
Show Gist options
  • Star 12 You must be signed in to star a gist
  • Fork 4 You must be signed in to fork a gist
  • Save vrushank-snippets/2169603 to your computer and use it in GitHub Desktop.
Save vrushank-snippets/2169603 to your computer and use it in GitHub Desktop.
PHP : Extract emails from a string
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));
@M-Shahbaz
Copy link

Including: test6[at]example.org
$regexp = '/([a-z0-9_\.\-])+(\@|\[at\])+(([a-z0-9\-])+\.)+([a-z0-9]{2,4})+/i';

@gajus
Copy link

gajus commented May 7, 2020

I've written something a bit more advanced for Node.js

https://github.com/gajus/extract-email-address

@bajramemini
Copy link

Thanks!

@hr1232
Copy link

hr1232 commented Apr 17, 2024

Including: test6[at]example.org $regexp = '/([a-z0-9_\.\-])+(\@|\[at\])+(([a-z0-9\-])+\.)+([a-z0-9]{2,4})+/i';

Just found this through a related Google search. At some point in time, people should stop propagating this fucked up stoneage-regexp.

Since 2001 we've had a few additional gTLDs. Amongst them are .museum and .travel, which don't fit this stoneage regex. Quite a few site even use the 1980s format of ([a-z0-9]{2,4})+ to parse the TLD part whichs keeps annoying me with my .name email address.

Nowadays (since 2013, so for over 10 years), anybody can register any TLD they want, so {2,4} ist just fucked up.

Also, maybe people should realize, that there are more characters in the world than the limited supply of 26 ones known by US and UK citizens. Here is some information for anybody who slept though 25 years of internet development:

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment