首页 > 解决方案 > php中特定电子邮件正文的键值对数组

问题描述

我有这样的电子邮件正文:

Title - Title Goes Here
Customer - Mr Abc Xyz
Terms And Conditions - You must accept our terms and conditions before sign in for any deals and 
offers.
You can refer our detailed information about this.

我曾经imap得到电子邮件正文['body']['html'],我想得到键值对数组,就像这样codeigniter3

Array(
       [Title] => Title Goes Here,
       [Customer] => Mr Abc Xyz,
       [Terms And Conditions] => You must accept our terms and conditions before sign in for any 
                                 deals and offers.You can refer our detailed information about this.
     )

我试图explode()获得高于预期的结果。

$arr = explode("-", $emailBodyContent);

但它给出了以下内容:

Array(
       [0] =>
       Title [1] => Title Goes Here,
       Customer [2] => Mr Abc Xyz,
       Terms And Conditions [3] => You must accept our terms and conditions before sign in for any 
                                 deals and offers.You can refer our detailed information about this.
     )

有人能帮助我吗 ?

标签: phpcodeignitercodeigniter-3

解决方案


由于您只是将其拆分为-,因此您不会考虑不同的数据行。复杂的部分是最后一个条目看起来好像它可能有多行。

此代码首先将其拆分为新行,然后处理每一行并将其拆分为-. 如果有 2 个部分 - 它将它们添加为一个新项目,如果没有(如最后一位),它只会将内容添加到添加的最后一个条目......

$emailBody = 'Title - Title Goes Here
Customer - Mr Abc Xyz
Terms And Conditions - You must accept our terms and conditions before sign in for any deals and 
offers.
You can refer our detailed information about this.';

$lines = explode("<br>", $emailBody);  
$output = [];
foreach ( $lines as $line ) {
    $lineSplit = explode("-", $line, 2);
    if ( count($lineSplit) == 2 ) {
        $lastKey = trim($lineSplit[0]);
        $output [ $lastKey ] = trim($lineSplit[1]);
    }
    else    {
        $output [ $lastKey ] .= " ".trim($line);
    }
}

print_r($output);

给...

Array
(
    [Title] => Title Goes Here
    [Customer] => Mr Abc Xyz
    [Terms And Conditions] => You must accept our terms and conditions before sign in for any deals and offers. You can refer our detailed information about this.
)

推荐阅读