PHP Script to Extract Email Address from any text
Posted on : 14-11-2007 | By : admin | In : PHP, PHP Code Examples, Programming
4
If you're new here, you may want to subscribe to my Newsletter. Thanks for visiting!
I have developed a function that you can embed in your PHP applications that will help you extract email addresses from a given piece of text.
I have tested this on a string of (actually 4 - 5 paragraphs) text and this has performed very well.
Please feel free to use this code in your applications and let me know if you face any issues.
$text = ' email@domain.com '; function parseTextForEmail($text) { $email = array(); $invalid_email = array(); $text = ereg_replace("[^A-Za-z._0-9@ ]"," ",$text); $token = trim(strtok($text, " ")); while($token !== "") { if(strpos($token, "@") !== false) { $token = ereg_replace("[^A-Za-z._0-9@]","", $token); //checking to see if this is a valid email address if(is_valid_email($email) !== true) { $email[] = strtolower($token); } else { $invalid_email[] = strtolower($token); } } $token = trim(strtok(" ")); } $email = array_unique($email); $invalid_email = array_unique($invalid_email); return array("valid_email"=>$email, "invalid_email" => $invalid_email); } function is_valid_email($email) { if (eregi("^[_a-z0-9-]+(\.[_a-z0-9-]+)*@[a-z0-9-]+(\.[a-z0-9-]+)*(\.([a-z]){2,4})$",$email)) return true; else return false; } var_dump(parseTextForEmail($text));
In the above program, you should pass a string of text to the method parseTextForEmail() that will return an array with valid and invalid email addresses.
Check the code and let me know if you have any issues or suggestions for improvements.
You can also check my PHP Tutorials - Starting with Creating a PHP5 Class









Very bloated way of pulling an email address from a piece of text.
An alternative would be preg_match,
preg_match_all(’/([\w\d\.\-\_]+)@([\w\d\.\_\-]+)/mi’, $string, $matches);
var_dump($matches);
Regex was done very quickly, but check out the results.
Verify the results using your verify func if you need to =]
Hi,your code works fine.Thankyou for giving such a nice function.
Thank you very much - works great for me.
It would be nice to have one to extract all url too!
when i tested this script of urs
named extracting email from string or text
this script raise an notice
Notice: Array to string conversion in G:\Program Files\EasyPHP 2.0b1\home\Demo\mailchk.php on line 38
array(2) { ["valid_email"]=> array(1) { [0]=> string(16) “email@domain.com” } ["invalid_email"]=> array(0) { } }
could u explain it me
thanks
amit