正则表达式从电子邮件地址获取电子邮件处理 [英] Regex Get Email handle from Email Address
问题描述
我有一个电子邮件地址可以是
$ email =x@example.com;
或 $ email = Johnny< x@example.com>
我想要
$ handle =x;
对于任一版本的$电子邮件。
如何在PHP中完成(假设正则表达式)。我不是很好的正则表达式。
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 either version of the $email.
How can this be done in PHP (assuming regex). I'm not so good at regex.
提前感谢
推荐答案
p>使用正则表达式<?([^<] +?)@
然后从 $ matches [1]
。
Use the regex <?([^<]+?)@
then get the result from $matches[1]
.
这是它的作用:
-
<?
匹配一个可选的 -
^<] +?
执行一个或多个不是^
或的字符的非贪婪匹配,
。 -
@
匹配@
电子邮件地址。
<?
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
这篇关于正则表达式从电子邮件地址获取电子邮件处理的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!