开发者

Regex Get Email handle from Email Address

I have an email address that could either be $email = "x@example.com"; or $email="Johnny <x@example.com>" I want to get $handle = "x"; for开发者_如何学Go either version of the $email. How can this be done in PHP (assuming regex). I'm not so good at regex.

Thanks in advance


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


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("ice.cream.bob@gmail.com"); // outputs ice.cream.bob@gmail.com
echo extract_email("Ice Cream Bob <ice.cream.bob@gmail.com>"); // outputs ice.cream.bob@gmail.com


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


$email = 'x@gmail.com';
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)

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜