Email is read in PHP

I need to read the 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 next process is:

  • Connection via IMAP
  • get nessage body

Now I want to read the specified data and you need to convert it to an array, for example:

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

I tried preg_match('/(?P<Pickup Address>\w+): (?P<Delivery Address>\d+)/', $body, $matches)

but this has some problem:

  • He doesn’t take a seat at Pickup Address
  • it provides an array in the format Array ( [0] => Address: 34 [PickupAddress] => Address [1] => Address [DeliveryAddress] => 34 [2] => 34 ) .

Basically, I need to save these fields in the database, and I cannot use the application here. Let me know if you have any other solution or some way to make it work.

+4
source share
3 answers

Something like that?

 $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 ) 
+5
source

It seems that you have chosen a solution, and he had difficulties with his solution. Yes, you could use regular expressions, but you will need to identify the problem much better than you already have. What if the string contains more than one :? What about empty lines? What if a data item spans more than one row (what can be done depending on how the email is encoded)?

While you can use the YAML parser, it is likely to overflow with 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; } 
+2
source

You can use this code:

 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 additional fields to just add them to the regular expression.

0
source

Source: https://habr.com/ru/post/1488062/


All Articles