如何使用 PHP 查找模式第一次出现的位置


How to find the position of the first occurrence of a pattern using PHP

我正在尝试找出一种解析电子邮件的方法。

我试图弄清楚如何搜索这种格式的文本的第一次出现

> On Mar 12, 2015, at 7:47 AM, Mike G <email@yourdomain.com> wrote:

文本将以 > On 开头,以 write 结尾:

2015年3月12日上午7点47分,迈克·

我怎样才能在 PHP 中找到它?

我能做到

   $msg = strpos($msg, '> On'); // to get the first position
   $msg = strstr($msg, '> On', true); // with PHP 5.3+ to get the text prior the first '> On '  

但我需要寻找类似的图案线才能更准确。

我尝试了以下代码:

$matches = '';
$pattern = "/ On*<[a-zA-Z0-9._-]@[a-zA-Z0-9._-]> wrote:/";
preg_match($pattern, $msg, $matches);
$msg = strstr($msg, $matches, true);

但我在文本中没有找到任何结果。

我认为这应该可以做到。如果空格是可选的,请将s+更改为 s*

preg_match('~>'s+.*?<([^>]*)>'s+wrote:~', '> On Mar 12, 2015, at 7:47 AM, Mike G <email@yourdomain.com> wrote:', $email);
echo $email[1];

如果您想更安全并且还需要"开"......

preg_match('~>'s+On.*?<([^>]*)>'s+wrote:~', '> On Mar 12, 2015, at 7:47 AM, Mike G <email@yourdomain.com> wrote:', $email);