开发者

Regular expression to replace period in name portion of e-mail header?

开发者 https://www.devze.com 2023-01-18 13:46 出处:网络
开发者_Go百科I am attempting to send an e-mail in PHP and the system is rejecting the e-mail because the name portion of the e-mail address contains a period like below:

开发者_Go百科I am attempting to send an e-mail in PHP and the system is rejecting the e-mail because the name portion of the e-mail address contains a period like below:

 Mr. Joe Nobody <jo_nobody@nowhere.com>

I am looking for an elegant solution to replace all periods that are not part of the e-mail address with either a space or no character at all. My problem is that the field I am replacing may contain more than one name/e-mail address combination like so:

 Mr. Joe Nobody <joe_nobody@here.com>, Mrs. Jane Noone <jane_noone@there.com>

Does anyone know of a way to do this in PHP using either standard string manipulation or a regular expression?


This regex pattern should work in PHP:

Search Pattern : \.(?=[^<]*<)

Replace Pattern: a space, underline, or none

for example:

  $email = 'Mr. Joe Nobody <joe_nobody@here.com>';
  $email = preg_replace('/\.(?=[^<]*<)/', '_', $email);


As noted in the comments above, this really shouldn't be required by an email system. Having said that, you could remove periods from the address, ignoring anything between "<..>" with the following

$a="Mr. Joe Nobody <joe_nobody@here.com>, Mrs. Jane Noone <jane_noone@there.com>";
$b=preg_replace("/([^<.]*)(\.|(<.*?>))/", "$1$3",$a); 
echo $b


$result = array();
foreach(imap_rfc822_parse_adrlist('Mr. Joe Nobody <joe_nobody@here.com>, Mrs. Jane Noone <jane_noone@there.com>','') as $address){
   $result[] = preg_replace('/\.\s?/',' ',$address->personal)
      .' <'.$address->mailbox
      .'@'.$address->host.'>';
}
echo implode(', ',$result);

But I do agree with Ether's comment, there should be no need.

0

精彩评论

暂无评论...
验证码 换一张
取 消