PHP function to validate a string of emails
New here? Learn about Bountify and follow @bountify to get notified of new bounties! x

Create a PHP function that validates a given String of emails.

  • The emails may be either comma, space, and/or new line separated.
  • If the string is valid, return the string with any extraneous white space stripped
  • If the string is invalid, return false

Valid examples

Valid (comma separated)

a@foobar.com, b@foobar.com, c@foobar.com

Valid (comma separated with extra spaces)

a@foobar.com,   b@foobar.com,   c@foobar.com

Valid (new line separated)

a@foobar.com
b@foobar.com
c@foobar.com

Valid (new line and comma separated)

a@foobar.com,
b@foobar.com,
c@foobar.com

Valid (space separated)

a@foobar.com b@foobar.com

Valid (comma and space separated)

a@foobar.com b@foobar.com, c@foobar.com

Valid (space separated with extra spaces)

a@foobar.com   b@foobar.com   c@foobar.com

Valid (single email)

a@foobar.com

Invalid examples

Invalid (b@foobar and c are not properly formatted email addresses)

a@foobar.com, b@foobar, c

Invalid (semi-colon separated)

a@foobar.com; b@foobar.com; c@foobar.com
awarded to Hasan Bayat

Crowdsource coding tasks.

2 Solutions


Hi, I think this may work:

function isValidEmail($email){

 $pattern = "^(([a-zA-Z0-9_\-\.]+)@([a-zA-Z0-9_\-\.]+)\.([a-zA-Z]{2,5}){1,25})+([ ;.](([a-zA-Z0-9_\-\.]+)@([a-zA-Z0-9_\-\.]+)\.([a-zA-Z]{2,5}){1,25})+)*$"; 
 if (eregi($pattern, $email)){ 
    return true; 
 } 
 else { 
    return false; 
 }    

}

Thanks for the submission. FYI as to why you didn't get the bounty despite submitting first: 1) eregi is a deprecated function, 2) you're returning a boolean value, not the input string with whitespace removed as specified. All of these things are surmountable, but it's what made Hasan's answer the bounty winner.
Difranco 4 months ago
Winning solution

You can use filter_var, it is a built-in php function.

And for validating a string of emails that separated with spaces, use split and validate each email:

function are_valid_emails ($emails_string) {
    $allValid = true;
    $emails = explode(" ", $emails_string);
    for ($i = 0; $i < count($emails); $i++) {
        $allValid &= is_valid_email($emails[$i]);
    }
    return $allValid;
}
function is_valid_email($email){ 
    return filter_var($email, FILTER_VALIDATE_EMAIL) !== false;
}

It is the simplest approach.

View Timeline