tags:

views:

80

answers:

7

Hi All,

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

My string is as follows

"First Last <[email protected]>"

I want to grab "[email protected]" and store it somewhere.

Thanks in advance!

+1  A: 

Check out:

http://www.phpfreaks.com/forums/index.php?topic=235338.0

Burton
+2  A: 

In your example, I'll do something like:

preg_match('/<([^>]+)>/', "First Last <[email protected]>", $matches);
$email = $matches[1];

Check out the official PHP documentation on preg_match.

shad
+1  A: 

You might want also to check here:

"How to Find or Validate an Email Address" on regular-expressions.info

npinti
+3  A: 

Without Regex (and likely much faster):

$string = "First Last <[email protected]>";
echo substr($string, strpos($string, '<') +1, -1);

or

echo trim(strstr("First Last <[email protected]>", '<'), '<>');

will both give

[email protected]

If you need to validate the final outcome, use

filter_var($eMailString, FILTER_VALIDATE_EMAIL);
Gordon
Though you'd have to add extra checks for non-matching input. Slight advantage for the regex here.
Tomalak
@Tomalak if there is no `<>` then the Regex (ex @shad's code) won't return anything either. At least with my 2nd example.
Gordon
Not exactly, because if the sting is ill-formed "bla <<nonsense> bla" a well-crafted regex would still work correctly (i.e.: no match), while substr() or strstr() would fail silently.
Tomalak
@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
A: 

You should consider using mailparse_rfc822_parse_addresses if possible.

Gumbo
Cool find. Too bad it's PECL though.
Gordon
A: 

Brilliant online tool - generates regex very easily, by only clicking :D Supports not only php, but many other languages and scripts :) Easy to use, saved my back many times ^^ Enjoy!!!

http://txt2re.com/

Nikola