4

我需要从中读取字段email

MOVE INFORMATION

Pickup Address: 34 Marigold Ln, Marlboro, NJ 07746

Delivery Address: 180 Prospect Park W, Apt 5, Brooklyn, NY 11215

Primary service dates:
Pack Date: N/A
Move Date: 6/6/2013

Other service dates:
Pack Date 2: N/A
Move Date2: N/A
Other Date: N/A

我遵循的过程是:

  1. 通过 IMAP 连接
  2. 得到 nessage 身体

现在我想读取指定的数据并需要将其转换为数组,如:

array( ' Pickup Address'=>'34 Marigold Ln, Marlboro, NJ 07746', 
       'Delivery Address'=>'180 Prospect Park W, Apt 5, Brooklyn, NY 11215'...)

我努力了preg_match('/(?P<Pickup Address>\w+): (?P<Delivery Address>\d+)/', $body, $matches)

但这有一些问题:

  1. 它不接受“取货地址”中的空格
  2. 它提供Array ( [0] => Address: 34 [PickupAddress] => Address [1] => Address [DeliveryAddress] => 34 [2] => 34 )格式的数组。

基本上我需要将这些字段保存在数据库中,我不能在这里使用附件。让我知道您是否有任何其他解决方案或任何使其工作的方法

4

3 回答 3

5

像这样的东西?

$string = 'MOVE INFORMATION

Pickup Address: 34 Marigold Ln, Marlboro, NJ 07746

Delivery Address: 180 Prospect Park W, Apt 5, Brooklyn, NY 11215

Primary service dates:
Pack Date: N/A
Move Date: 6/6/2013

Other service dates:
Pack Date 2: N/A
Move Date2: N/A
Other Date: N/A';

preg_match_all('#(.*?):(.*)#m', $string, $m);
if(isset($m[1], $m[2])){
    $array = array_combine($m[1], $m[2]);
    print_r($array);
}

输出:

Array
(
    [Pickup Address] =>  34 Marigold Ln, Marlboro, NJ 07746
    [Delivery Address] =>  180 Prospect Park W, Apt 5, Brooklyn, NY 11215
    [Primary service dates] => 
    [Pack Date] =>  N/A
    [Move Date] =>  6/6/2013
    [Other service dates] => 
    [Pack Date 2] =>  N/A
    [Move Date2] =>  N/A
    [Other Date] =>  N/A
)
于 2013-06-25T12:21:25.777 回答
2

您似乎已经选择了一个解决方案,但很难使其适合该问题。是的,你可以使用正则表达式——但你必须比你已经拥有的更好地定义问题。如果一行包含多个 ':' 怎么办?空行怎么办?如果一个数据项跨越多行(这可能取决于电子邮件的编码方式)怎么办?

虽然您可以使用YAML 解析器,但对于简单的布局来说,这可能有点过头了:

$data=array();
while ($line=fgets($file_handle)) {
     $key=trim(substr($line, 0, strpos($line, ':')));
     $value=trim(substr($line, strpos($line, ':')+1));
     if ($key && $value) $data[$key]=$value; 
}
于 2013-06-25T12:45:30.167 回答
0

你可以使用这样的代码:

preg_match_all("/(Pickup Address|Delivery Address): *(.*)/", $email, $match);
$result = array();
foreach($match[1] as $i => $key) {
    $result[$key] = $match[2][$i];
}
print_r($result);

如果您想要更多字段,只需将它们添加到正则表达式。

于 2013-06-25T12:25:12.287 回答