st4ck0v3rfl0w
st4ck0v3rfl0w

Reputation: 6755

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

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!

Upvotes: 9

Views: 7480

Answers (6)

casraf
casraf

Reputation: 21684

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];
}

Upvotes: 3

Erik
Erik

Reputation: 20712

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.

Upvotes: 6

Ben Rowe
Ben Rowe

Reputation: 28701

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, '<')));

Upvotes: 1

ghostdog74
ghostdog74

Reputation: 342313

$str ="First Last <[email protected]>";
$s = explode("@",$str);
$t = explode("<",$s[0]);
print end($t);

Upvotes: 6

Anon.
Anon.

Reputation: 59973

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.

Upvotes: 1

No Refunds No Returns
No Refunds No Returns

Reputation: 8336

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.

Upvotes: 2

Related Questions