views:

72

answers:

3

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 <[email protected]>

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 <[email protected]>, Mrs. Jane Noone <[email protected]>

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

+1  A: 

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 <[email protected]>, Mrs. Jane Noone <[email protected]>";
$b=preg_replace("/([^<.]*)(\.|(<.*?>))/", "$1$3",$a); 
echo $b
thinker--
+1  A: 

This regex pattern should work in PHP:

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

Replace Pattern: a space, underline, or none

for example:

  $email = 'Mr. Joe Nobody <[email protected]>';
  $email = preg_replace('/\.(?=[^<]*<)/', '_', $email);
Vantomex
+1 - Thanks for the answer. I'll repost if I find a better way to handle this situation, but you did indeed answer my question with an elegant solution, so thank you very much :-)
Topher Fangio
+1  A: 
$result = array();
foreach(imap_rfc822_parse_adrlist('Mr. Joe Nobody <[email protected]>, Mrs. Jane Noone <[email protected]>','') 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.

Wrikken
+1 - I agree that this shouldn't be necessary, but I haven't found a way around it yet. I'll repost here if I find a better solution.
Topher Fangio