0

I wondered if anyone has any idea how to best do this in php.

I have a string in a variable and I want to pull an email address from it (if one exists).

The string could be along the lines of :

"My email address is myemail@mydomain.com and I would appreciate it if you contact me"

I know I can validate if an email is valid or not but wondered how to search a string and extract the email.

IE: I can use filters to validate the email but I am stuck at how to search the string to see if it has an email.

Chris Carter
  • 25
  • 1
  • 7
  • http://php.net/manual/en/function.preg-match.php – AbraCadaver Jan 10 '17 at 17:29
  • 1
    A short hint to get you going: read about regular expressions. – arkascha Jan 10 '17 at 17:32
  • Thanks for that @AbraCadaver - Much appreciated. – Chris Carter Jan 10 '17 at 18:44
  • @arkascha - No, i'm not scraping email addresses from the web. If I wanted to do that I would use one of the many scraper libs around. The string is coming from a user filled in textarea. – Chris Carter Jan 10 '17 at 18:44
  • I'm trying to figure out what that preg_match needs tweaking @AbraCadaver but not getting far. It is grabbing the email address but not the tld from the end. So myemail@mydomain.com matches as myemail@mydomain – Chris Carter Jan 10 '17 at 19:34
  • Just found this : http://stackoverflow.com/questions/33865113/extract-email-address-from-string-php That seems to do the trick. Thank you everyone for your help - I feel a little foolish that I didn't find the answer from search on SO ! – Chris Carter Jan 10 '17 at 19:43
  • Posted a better one that will capture what you want, but then still needs to be validated. – AbraCadaver Jan 10 '17 at 19:49
  • Possible duplicate of [How to get email address from a long string](http://stackoverflow.com/questions/1028553/how-to-get-email-address-from-a-long-string) – Syed Waqas Bukhary Jan 10 '17 at 20:20

1 Answers1

3

This should work fairly well. You'll get things that appear to be an email address though they may not be valid. Then use filter_var() to check if it's valid.

preg_match('/\b[^\s]+@[^\s]+/', $string, $match);
echo $match[0];

Match:

  • A word boundary \b followed by
  • NOT white space [^\s]+ followed by
  • A @ followed by
  • NOT white space [^\s]+
AbraCadaver
  • 78,200
  • 7
  • 66
  • 87