Parse RFC 822 compliant addresses in a TO header

后端 未结 2 538
無奈伤痛
無奈伤痛 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)?<?([a-z0-9._%-]+@[a-z0-9.-]+\\.[a-z]{2,4})>?$/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.

    0 讨论(0)
  • 2021-01-14 05:41

    I don't know that RFC, but if the format is always as you showed then you can try something like:

    preg_match_all("/\"([^\"]*)\"\\s+<([^<>]*)>/", $string, $matches);
    print_r($matches);
    
    0 讨论(0)
提交回复
热议问题