Address.php
2.5 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
<?php
namespace Lib\Imap\Parse;
/**
 * @author:dc
 * @time 2024/9/11 11:17
 * Class Address
 * @package Imap\Parse
 */
class Address {
    public string $name = '';
    public string $email = '';
    private string $raw;
    private function __construct(string $address){
        $this->raw = $address;
        if($this->raw){
            $this->parse();
        }
    }
    /**
     * 创建一个地址类
     * @param string $address
     * @return static
     * @author:dc
     * @time 2024/9/11 11:37
     */
    public static function make(string $address):self {
        return new self($address);
    }
    /**
     * 解析地址
     * 情况1  "name" <xxx@email.com>
     * 情况2  "name" xxx@email.com
     * 情况3  name xxx@email.com
     * 情况4  xxx@email.com
     * @author:dc
     * @time 2024/9/11 11:39
     */
    private function parse(){
        $email = self::pregEmail($this->raw);
        if(!empty($email)){
            $this->email = $email;
            $this->name = trim($this->raw);
            $len = strlen($email);
            if(substr($this->name,-1)=='>'){
                $len += 2;
            }
            $this->name = substr($this->name,0,-$len);
            $this->name = trim($this->name);
            $this->name = trim($this->name,'"');
        }
        if($this->name){
//            $this->name = DeCode::decode($this->name);
            $this->name = Header::mime_decode($this->name);
        }else{
            $this->name = explode('@',$this->email)[0]??'';
        }
    }
    /**
     * 匹配邮箱
     * @param $str
     * @return string
     * @author:dc
     * @time 2024/9/11 11:43
     */
    private function pregEmail(string $str):string {
        preg_match_all('/\w+([-+.]\w+)*@\w+([-.]\w+)*\.\w+([-.]\w+)*/',$str,$email);
        if(!empty($email[0])){
            $email = end($email[0]);
        }else{
            $email = '';
        }
        if(empty($email)){
            // 邮箱2
            preg_match_all('/[a-zA-Z0-9._-]+@[a-zA-Z0-9.-]+\.[a-zA-Z]{2,}/',$str,$email);
            if(!empty($email[0])){
                $email = end($email[0]);
            }else{
                $email = '';
            }
        }
        return str_replace(['<','>'],'',$email);
    }
    /**
     * @return string
     */
    public function getRaw(): string
    {
        return $this->raw;
    }
    public function toArray():array {
        return [
            'email' =>  $this->email,
            'name'  =>  $this->name
        ];
    }
}