如何提取电子邮件&;使用PHP的完整电子邮件文本中的名称


How to extract Email & Name from Full Email text using PHP?

我有一个字符串作为

$email_string='Aslam Doctor <aslam.doctor@gmail.com>';

我想从中提取Name&使用PHP发送电子邮件?这样我就可以得到

$email='aslam.doctor@gmail.com';
$name='Aslam Doctor'

提前谢谢。

尽管人们可能会推荐正则表达式,但我还是说使用explode()。"分解"使用任意分隔符将字符串拆分为多个子字符串。在这种情况下,我使用'<'作为分隔符,可以立即去除名称和电子邮件之间的空白。

$split = explode(' <', $email_string);
$name = $split[0];
$email = rtrim($split[1], '>');

rtrim()将从字符串末尾修剪'>'字符。

使用explode+list:

$email_string = 'Aslam Doctor <aslam.doctor@gmail.com>';
list($name, $email) = explode(' <', trim($email_string, '> '));

如果您可以使用IMAP扩展,那么imap_rfc822_parse_adrlist函数就是您所需要的。

/通过https://stackoverflow.com/a/3638433/204774

文本变量有一个段落。其中包括两封电子邮件。使用extractemailsfromstring()函数,我们从该段落中提取这些邮件。preg_match_all函数将从输入中返回所有带有正则表达式的匹配字符串。

function extract_emails_from_string($string){
  preg_match_all("/['._a-zA-Z0-9-]+@['._a-zA-Z0-9-]+/i", $string, $matches);
  return $matches[0];
}

$text = "Please be sure to answer the Please arun1@email.com be sure to answer the Please be sure to answer the Please be sure to answer the Please be sure to answer the Please be sure to answer the Please be sure to answer the  arun@email.com";
$emails = extract_emails_from_string($text);
print(implode("'n", $emails));

这就是我使用的-适用于带有和不带有尖括号格式的电子邮件地址。因为我们是从右到左搜索的,所以这也适用于那些奇怪的实例,其中名称段实际上包含<字符:

$email   = 'Aslam Doctor <aslam.doctor@gmail.com>';
$address = trim(substr($email, strrpos($email, '<')), '<>');