我需要阅读此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
我遵循的流程是:
现在我想读取指定的数据,需要将其转换为数组,如:
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)
但那有一些问题:
Array ( [0] => Address: 34 [PickupAddress] => Address [1] => Address [DeliveryAddress] => 34 [2] => 34 )
格式提供数组。基本上我需要在数据库中保存这些字段,我不能在这里使用附件。如果您有任何其他解决方案或以任何方式使其正常工作,请告诉我
答案 0 :(得分: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
)
答案 1 :(得分:2)
您似乎已经选择了一个解决方案,然后很难使其适应问题。是的,你可以使用正则表达式 - 但是你必须比现有的更好地定义问题。如果一行包含多个':'怎么办?空行怎么样?如果数据项跨越多行(根据电子邮件的编码方式可能会这样做)会怎样?
虽然您可以使用YAML parser,但对于简单的布局来说可能有点过分了:
$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;
}
答案 2 :(得分: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);
如果你想要更多的字段,只需将它们添加到正则表达式。