mailparse_rfc822_parse_addresses()
(PECL mailparse >= 0.9.0)
Parse RFC 822 compliant addresses
说明
mailparse_rfc822_parse_addresses(string $addresses): array
Parses a » RFC 822 compliant recipient list, such as that found in theTo:header.
参数
- $addresses
A string containing addresses, like in:Wez Furlong <wez@example.com>, doe@example.com
Note:
This string must not include the header name.
返回值
Returns an array of associative arrays with the following keys for each recipient:
display | The recipient name, for display purpose. If this part is not set for a recipient, this key will hold the same value asaddress. |
address | The email address |
is_group | TRUE if the recipient is a newsgroup,FALSE otherwise. |
范例
Example #1 mailparse_rfc822_parse_addresses() example
<?php $to = 'Wez Furlong <wez@example.com>, doe@example.com'; var_dump(mailparse_rfc822_parse_addresses($to)); ?>
以上例程会输出:
array(2) { [0]=> array(3) { ["display"]=> string(11) "Wez Furlong" ["address"]=> string(15) "wez@example.com" ["is_group"]=> bool(false) } [1]=> array(3) { ["display"]=> string(15) "doe@example.com" ["address"]=> string(15) "doe@example.com" ["is_group"]=> bool(false) } }
<?php // input: My Test Email <some.test.email@somewhere.net> function get_displayname_from_rfc_email($rfc_email_string) { // match all words and whitespace, will be terminated by '<' $name = preg_match('/[\w\s]+/', $rfc_email_string, $matches); $matches[0] = trim($matches[0]); return $matches[0]; } // Output: My Test Email function get_email_from_rfc_email($rfc_email_string) { // extract parts between the two parentheses $mailAddress = preg_match('/(?:<)(.+)(?:>)$/', $rfc_email_string, $matches); return $matches[1]; } // Output: some.test.email@somewhere.net ?>
If for some reason you cannot compile mailparse into your install of PHP, you will also find an extremely similar function in the Mail_MIME PEAR class, specifically in mimeDecode.php.
An alternative to the mailparse_rfc822_parse_addresses() function is Mail_RFC822::parseAddressList() from Pear: http://pear.php.net/manual/en/package.mail.mail.php It parses the string and returns a structured tree of data. Returns a pear_error object if the string is not valid. Example: require_once "PEAR.php"; require_once "Mail/RFC822.php"; $addr= "Hi <hi@world.org>"; $res= Mail_RFC822::parseAddressList($addr); if (PEAR::isError($res)) die("NOT VALID: " . $res->getMessage() . "\n"); echo "OK. Data:\n"; print_r($res);