tags:

views:

83

answers:

6

Hi all,

I have the following String

First Last <[email protected]>

I would like to extract

"first.last" 

from the email string using regex & PHP. How to go about this?

Thanks in advance!

+1  A: 

Can't you just use a split function instead? I don't use PHP but seems like this would be far simpler if it's available.

No Refunds No Returns
+1  A: 

If that's the exact format you'll get, then matching against the regex

/<([^@<>]+)@([^@<>]+)>/

will give you e.g. first.last in capture group 1 and email.com in capture group 2.

Anon.
Note that this chokes on email addresses containing multiple @s. I doubt this is a problem for the vast majority of users though - and in this case, a solution which works 99.9% of the time takes less than 0.1% of the effort involved in getting the last 0.1% working correctly.
Anon.
with /slightly/ more work, you can find the last @ in the string knowing that according to the RFC, the name is the portion before that final @.
Erik
+2  A: 
$str ="First Last <[email protected]>";
$s = explode("@",$str);
$t = explode("<",$s[0]);
print end($t);
ghostdog74
Ghostdog, I like this solution too, but to be fair my question asked for a regex. But nonetheless your solution works great, thanks for your response!
st4ck0v3rfl0w
Btw, what does print end() do?
st4ck0v3rfl0w
fair enough. Its your choice. I just presented a simpler alternative, for your particular string sample. end($t) is the last element of the array. check the PHP docs for more
ghostdog74
A: 

No need to use regexp; much more efficient to use some simple string functions.

$string = 'First Last <[email protected]>';
$name = trim(substr($string, 0, strpos($string, '<')));
Ben Rowe
Except you're getting "First Last" as your result, not "first.last"
Erik
+2  A: 

I know the answer was already accepted, but this will work on any valid email address in the format of: Name <identifier@domain>

// Yes this is a valid email address
$email = 'joey <"joe@work"@example.com>';

echo substr($email, strpos($email,"<")+1, strrpos($email, "@")-strpos($email,"<")-1);
// prints: "joe@work"

Most of the other posted solutions will fail on a number of valid email addresses.

Erik
very nice Erik, I'm accepting this.
st4ck0v3rfl0w
A: 

This is a lot easier (after checking that the email IS valid):

$email = '[email protected]';
$split = explode('@',$email);
$name = $split[0];
echo "$name"; // would echo "my.name"

To check validity, you could do this:

function isEmail($email) {
    return (preg_match('/[\w\.\-]+@[\w\.\-]+\.\[w\.]/', $email));
}
if (isEmail($email)) { ... }

As for extracting the email out of First Last <[email protected]>,

function returnEmail($contact) {
    preg_match('\b[\w\.\-]+@[\w\.\-]+\.\[w\.]\b', $contact, $matches);
    return $matches[0];
}
henasraf