Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Regex: How to strip email before "@" symbol?

Tags:

string

regex

php

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!

like image 392
st4ck0v3rfl0w Avatar asked Feb 24 '10 01:02

st4ck0v3rfl0w


4 Answers

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.

like image 117
Erik Avatar answered Nov 03 '22 15:11

Erik


$str ="First Last <[email protected]>";
$s = explode("@",$str);
$t = explode("<",$s[0]);
print end($t);
like image 26
ghostdog74 Avatar answered Nov 03 '22 15:11

ghostdog74


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];
}
like image 21
casraf Avatar answered Nov 03 '22 15:11

casraf


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.

like image 2
No Refunds No Returns Avatar answered Nov 03 '22 15:11

No Refunds No Returns