1

I need to parse email body(it can be both text and html), of forwarded email, to find original sender of email(both name and email).

So lets say that John send email to Steve, and Steve forward to Matt. So, in most clients message will look like:

From: John Smith [mailto:john@example.com]
Sent: 02 March 2012 AM 01:23
To: 'Steve'
Subject: Hello Steve

Or

---------- Forwarded message ----------
From: John Smith <ejohn@example.com>
Date: 02 March 2012 AM 01:23
Subject: Hello Steve
To: Steve <steve@example.com>

So, how can I extract from name and from email values in those two cases? Please note that I need to extract only first appearance of this text, because there can be multiple appearances of lines "From:...".

4

1 回答 1

3

使用正则表达式

/^From:\s+(.*?)\s*(?:\[mailto:|<)(.*?)(?:[\]>])$/

您将获得第一个匹配名称和第二个匹配电子邮件地址


<?php
  $string = "...";
  $pattern = '/^From:\s+(.*?)\s*(?:\[mailto:|<)(.*?)(?:[\]>])$/mi';
  preg_match($pattern, $string, $matches);
  print_r($matches);
?>

有时也有'"在名字的开头和结尾处。要消除这种情况,请使用:

/^From:\s+["']?(.*?)["']?\s*(?:\[mailto:|<)(.*?)(?:[\]>])$/
于 2012-04-20T11:57:18.610 回答