0

How do I grab the email inside a string using Regex?

My string is as follows

"First Last <first.last@email.com>"

I want to grab "first.last@gmail.com" and store it somewhere.

Thanks in advance!

st4ck0v3rfl0w
  • 6,665
  • 15
  • 45
  • 48
  • Check out: http://www.phpfreaks.com/forums/index.php?topic=235338.0 – Burton Feb 22 '10 at 17:18
  • You might want also to check here: >["How to Find or Validate an Email Address"](http://www.regular-expressions.info/email.html) on regular-expressions.info – npinti Feb 22 '10 at 17:21
  • You should consider using [`mailparse_rfc822_parse_addresses`](http://php.net/mailparse_rfc822_parse_addresses) if possible. – Gumbo Feb 22 '10 at 18:07

3 Answers3

3

Without Regex (and likely much faster):

$string = "First Last <first.last@email.com>";
echo substr($string, strpos($string, '<') +1, -1);

or

echo trim(strstr("First Last <first.last@email.com>", '<'), '<>');

will both give

first.last@email.com

If you need to validate the final outcome, use

filter_var($eMailString, FILTER_VALIDATE_EMAIL);
Gordon
  • 312,688
  • 75
  • 539
  • 559
  • Though you'd have to add extra checks for non-matching input. Slight advantage for the regex here. – Tomalak Feb 22 '10 at 17:39
  • @Tomalak if there is no `<>` then the Regex (ex @shad's code) won't return anything either. At least with my 2nd example. – Gordon Feb 22 '10 at 17:44
  • Not exactly, because if the sting is ill-formed "bla < bla" a well-crafted regex would still work correctly (i.e.: no match), while substr() or strstr() would fail silently. – Tomalak Feb 22 '10 at 17:48
  • @Tomalak Ah, I see. Yes, but you could still run it through `filter_var` to validate it, though in the UseCase of the OP it looks like he's getting valid eMails right from the start. Looks like he's parsing mail headers to me. – Gordon Feb 22 '10 at 18:01
2

In your example, I'll do something like:

preg_match('/<([^>]+)>/', "First Last <first.last@email.com>", $matches);
$email = $matches[1];

Check out the official PHP documentation on preg_match.

Sam Alba
  • 861
  • 1
  • 9
  • 10
2
^[^<]*<([^>]*)>$

For the rest, see Using a regular expression to validate an email address

Community
  • 1
  • 1
edgar.holleis
  • 4,803
  • 2
  • 23
  • 27