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.
<?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];
?>
$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); });
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