Remove invalid email format in PHP

ぃ、小莉子 提交于 2019-12-08 00:23:36

问题


Array (
    [0] => myemail@domain.com
    [1] => mysecondemail@domain.com
    [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.


回答1:


<?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];
?>



回答2:


$valid = array_filter($emails, create_function('$s', 'return filter_var($s, FILTER_VALIDATE_EMAIL);'));

Or for PHP 5.3+:

$valid = array_filter($emails, function ($s) { return filter_var($s, FILTER_VALIDATE_EMAIL); });



回答3:


Basic solution is simple and doesn't require regex

  $isvalid = filter_var('myname@anydomain.com', FILTER_VALIDATE_EMAIL));

But...

One line solution just doesn't exist (using regex or something else).

To learn more about valid e-mail addresses, follow references below.

References:

  • RFC 821: SIMPLE MAIL TRANSFER PROTOCOL
  • RFC 822: STANDARD FOR THE FORMAT OF ARPA INTERNET TEXT MESSAGES
  • RFC 1123: Requirements for Internet Hosts -- Application and Support
  • RFC 2142: MAILBOX NAMES FOR COMMON SERVICES, ROLES AND FUNCTIONS
  • RFC 2821: Simple Mail Transfer Protocol (SMTP) - replaced with RFC 821
  • RFC 2822: Internet Message Format - replaced with RFC 822
  • RFC 3696: Application Techniques for Checking and Transformation of Names
  • RFC 5233: Sieve Email Filtering: Subaddress Extension
  • RFC 5321: Simple Mail Transfer Protocol (SMTP)
  • RFC 5322: Internet Message Format
  • RFC 5335: Internationalized Email Headers

Some valid examples are:

  • 甲斐@黒川.日本
  • Rδοκιμή@παράδειγμα
  • Pelé@example.com
  • jsmith@[192.168.2.1]
  • abc\@xyz@domain.com

Those addreses are not compilant with RFC 5322 standard, but they are still valid.

Even you validate some addresses as correct, nothing can guarantee that your e-mail server will accept them.



来源:https://stackoverflow.com/questions/5738970/remove-invalid-email-format-in-php

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!