Reputation: 2128
I have an email address that could either be
$email = "[email protected]";
or $email="Johnny <[email protected]>"
I want to get
$handle = "x";
for either version of the $email.
How can this be done in PHP (assuming regex). I'm not so good at regex.
Thanks in advance
Upvotes: 2
Views: 2661
Reputation: 180
Here is a complete PHP solution based on marcog's answer
function extract_email($email_string) {
preg_match("/<?([^<]+?)@([^>]+?)>?$/", $email_string, $matches);
return $matches[1] . "@" . $matches[2];
}
echo extract_email("[email protected]"); // outputs [email protected]
echo extract_email("Ice Cream Bob <[email protected]>"); // outputs [email protected]
Upvotes: 3
Reputation: 138337
Use the regex <?([^<]+?)@
then get the result from $matches[1]
.
Here's what it does:
<?
matches an optional <
.[^<]+?
does a non-greedy match of one or more characters that are not ^
or <
.@
matches the @
in the email address.A non-greedy match makes the resulting match the shortest necessary for the regex to match. This prevents running past the @
.
Rubular: http://www.rubular.com/r/bntNa8YVZt
Upvotes: 3
Reputation: 1925
$email = '[email protected]';
preg_match('/([a-zA-Z0-9\-\._\+]+@[a-z0-9A-Z\-\._]+\.[a-zA-Z]+)/', $email, $regex);
$handle = array_shift(explode('@', $regex[1]));
Try that (Not tested)
Upvotes: 0
Reputation: 2454
Just search the string using this basic email-finding regex: \b[A-Z0-9._%+-]+@[A-Z0-9.-]+.[A-Z]{2,4}\b It will match any email in any text, and in your first string it will match the whole string, and in the second, only the part of the string that is e-mail.
To quickly learn regexp this is the best place: http://www.regular-expressions.info
Upvotes: 0