Search code examples
phpregexpreg-matchextractemail-address

PHP preg_match result


This PHP function working just fine:

if (preg_match ("/<(\S+@\S+\w)>.*\n?.*55[0-9]/i",$body,$match)) {
echo "found!";
}

in

This message was created automatically by mail delivery software.

A message that you sent could not be delivered to one or more of its
recipients. This is a permanent error. The following address(es) failed:

[email protected]
SMTP error from remote mail server after RCPT TO:<[email protected]>:
host mx3.hotmail.com [65.54.188.72]: 550 Requested action not taken:
mailbox unavailable

But if I use the same php function in this case:

A message that you sent could not be delivered to one or more of its 
recipients. This is a permanent error. The following address(es) failed:

[email protected]
SMTP error from remote mail server after end of data:
host d.mx.mail.yahoo.com [209.191.88.254]: 554 delivery error:
dd This user doesn't have a yahoo.com account ([email protected]) [0] -  mta1010.mail.mud.yahoo.com

The preg_match function does not give any results. What am I doing wrong?


Solution

  • You are basically looking for a email addressing enclosed in < and >.

    Your first input has it but the second input does not: It has no email id in < > hence you don't get a match.

    Edit: (after your comment):

    Looking at the 2 samples given by you the email id appears between the string failed: and the error code starting with 55. You can make use of the preg_match for this as:

    if(preg_match('/failed:.*?(\b[A-Z0-9._%+-]+@[A-Z0-9.-]+\.[A-Z]{2,4}\b).*55[\d]/is',$str,$m)) {
           echo "Bounced email ".$m[1]."\n";
    }
    

    Ideone link