使用preg_match拆分邮件头

时间:2012-05-22 17:00:43

标签: php pcre

我必须通过电子邮件发送标题,我想提取不同的数据:来自主题,日期等。

$mail1 = 'From: <encuestas@despegar.com>
To: 4fb661d55e409@ventas.ciudades.com
Subject: Califique nuestro servicio
Date: Sat, 19 May 2012 10:39:04 -0400
Message-ID: <3b6401cd35cd$23d08b90$0c01010a@despexds.net>
MIME-Version: 1.0';

$mail2 = 'Date: Fri, 21 Oct 2011 13:42:46 +0000 (GMT)
From: "Decolar.com" <non-reply@despegar.com>
To: 4ea15be894aca@ventas.ciudades.com
Message-ID: <2009175400.15674.1319204566275.JavaMail.root@uns02>
Subject: =?UTF-8?Q?Decolar.com_-_Solicita=C3=A7=C3=A3o_?=
 =?UTF-8?Q?de_compra_-_N=C3=BAmero:10603789?=
MIME-Version: 1.0';


preg_match("/Subject: (.)*(Date|Message-ID|From|To|MIME-Version):/s",$mail1,$m);        
print_r($m);       

我正在使用上面的代码来获取主题,但结果不是预期的。

对于mail1,我得到:

Array
(
    [0] => Subject: Califique nuestro servicio
Date: Sat, 19 May 2012 10:39:04 -0400
Message-ID: <3b6401cd35cd$23d08b90$0c01010a@despexds.net>
MIME-Version:
    [1] => 

    [2] => MIME-Version
)

对于mail2,我得到:

Array
(
    [0] => Subject: =?UTF-8?Q?Decolar.com_-_Solicita=C3=A7=C3=A3o_?=
 =?UTF-8?Q?de_compra_-_N=C3=BAmero:10603789?=
MIME-Version:
    [1] => 

    [2] => MIME-Version
)

在这两种情况下,主题都是空的。

2 个答案:

答案 0 :(得分:5)

我可能会这样做:

function normalize_array($arr) {
    for ($res = array(), $i = 0; $i < count($arr); $i+=2) {
        $key = strtr($arr[$i],array(': '=>'','-'=>'_'));
        $res[$key] = $arr[$i+1];
    }
    return $res;
}

$mailData = normalize_array(preg_split('~([\w-]+: )~',$mail1,-1,PREG_SPLIT_DELIM_CAPTURE|PREG_SPLIT_NO_EMPTY));
print_r($mailData);

将返回:

Array
(
    [From] => <encuestas@despegar.com>

    [To] => 4fb661d55e409@ventas.ciudades.com

    [Subject] => Califique nuestro servicio

    [Date] => Sat, 19 May 2012 10:39:04 -0400

    [Message_ID] => <3b6401cd35cd$23d08b90$0c01010a@despexds.net>

    [MIME_Version] => 1.0
)

答案 1 :(得分:1)

正则表达式应该是:

/Subject: (.*)\b/