Parse RFC 822 compliant addresses in a TO header

后端 未结 2 561
無奈伤痛
無奈伤痛 2021-01-14 05:06

I would like to parse an email address list (like the one in a TO header) with preg_match_all to get the user name (if exists) and the E-mail. Something similar to mailparse

2条回答
  •  暗喜
    暗喜 (楼主)
    2021-01-14 05:39

    Finally I did it:

    public static function parseAddressList($addressList)
    {
        $pattern = '/^(?:"?((?:[^"\\\\]|\\\\.)+)"?\s)??$/i';
        if (($addressList[0] != '<') and preg_match($pattern, $addressList, $matches)) {
            return array(
                array(
                    'name' => stripcslashes($matches[1]),
                    'email' => $matches[2]
                )
            );
        } else {
            $parts = str_getcsv($addressList);
            $result = array();
            foreach($parts as $part) {
                if (preg_match($pattern, $part, $matches)) {
                    $item = array();
                    if ($matches[1] != '') $item['name'] = stripcslashes($matches[1]);
                    $item['email'] =  $matches[2];
                    $result[] = $item;
                }
            }
            return $result;
        }
    }
    

    But I'm not sure it works for all cases.

提交回复
热议问题