Reputation: 145
I need to read fields from this 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
The process I am following is:
Now I want to read specified data and need to convert it into array like:
array( ' Pickup Address'=>'34 Marigold Ln, Marlboro, NJ 07746',
'Delivery Address'=>'180 Prospect Park W, Apt 5, Brooklyn, NY 11215'...)
I have tried preg_match('/(?P<Pickup Address>\w+): (?P<Delivery Address>\d+)/', $body, $matches)
but thats having some problem:
Array ( [0] => Address: 34 [PickupAddress] => Address [1] => Address [DeliveryAddress] => 34 [2] => 34 )
format.Basically I need to save these fields in database and I can not use attachment here. Let me know if you have any other solution or any way to make it work
Upvotes: 4
Views: 278
Reputation: 48357
You seem to have chosen a solution then are having difficulty making it fit the problem. Yes you could use regexes - but you're going to have to define the problem a lot better than you already have. What if a line contains more than one ':'? What about blank lines? What if a data item spans more than one line (which it might do depending on how the email is encoded)?
While you could use a YAML parser, it's probably overkill for a simple layout:
$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;
}
Upvotes: 2
Reputation: 66518
You can use code like this:
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);
if you want more fields just add them to the regex.
Upvotes: 0
Reputation: 14921
Something like this ?
$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);
}
Output:
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
)
Upvotes: 5