Search code examples
phparraysvalidationfunctionemail-validation

Remove invalid email format in PHP


Array (
    [0] => [email protected]
    [1] => [email protected]
    [2] => invalidEmail.com
)

Notice that the third array value is invalid email format. How do I remove it by using/creating a function? I need the valid email to implode("," the valid email) before sending an email using the mail() function.


Solution

  • <?php
    $len=count($array);
    for ($i=0;$i<$len;$i++)
      if (preg_match('^[a-z0-9!#$%&*+/=?^_`{|}~-]+(?:.[a-z0-9!#$%&*+/=?^_`{|}~-]+)*@(?:[a-z0-9](?:[a-z0-9-]*[a-z0-9])?.)+(?:[a-z]{2,4}|museum|travel)$/i',$array[$i]))
          echo $array[$i];
    ?>