-2

I'm using the following function to determine if an e-mail is valid. I have a customer with an e-mail address that has a hyphen in the domain name: Example@some-thing.com and it's coming back as invalid. Unfortunately, I don't understand regex. Could someone help me fix it to accept his e-mail?

function isValidEmail($email)
{
    $regex = "/([a-z0-9_]+|[a-z0-9_]+\.[a-z0-9_]+)@(([a-z0-9]|[a-z0-9]+\.[a-z0-9]+)+\.([a-z]{2,4}))/i"; 

    if(!preg_match($regex, $email)) { 
        return false;   } 
    else { 
    return true;
    } 
}
Funk Forty Niner
  • 74,450
  • 15
  • 68
  • 141
DanielRead
  • 2,288
  • 1
  • 23
  • 34
  • 2
    why not just use [filter_var()](http://php.net/manual/en/filter.filters.validate.php) instead of trying to roll your own? Email addresses are complex enough as is. trying to write your own regex to validate them is insane... – Marc B Feb 03 '15 at 20:29
  • @Dagon Seems like it's just us mere peasants that find the duplicates. Edit: Closed. Thanks for taking "the time" to find the duplicate. – Funk Forty Niner Feb 03 '15 at 20:35
  • 1
    @Fred-ii- its my special super power. I'm *"there's nothing new under the sun"* man –  Feb 03 '15 at 20:36
  • @Dagon Exactly. Edited my comment above ;-) – Funk Forty Niner Feb 03 '15 at 20:37

2 Answers2

5

Do not use a custom regular expression, use PHP's built in filter_var():

function isValidEmail($email) {
    return filter_var($email, FILTER_VALIDATE_EMAIL);
}
Jason McCreary
  • 71,546
  • 23
  • 135
  • 174
0

Don't bother trying to recreate this on your own, email validation using regex can get extremely complex. PHP provides a useful function filter_var() that can be used for this purpose.

Simply use:

if (filter_val($email_address, FILTER_VALIDATE_EMAIL)) {
    // The email address is valid!
}
else
    // The email address is invalid!
Thijs Riezebeek
  • 1,762
  • 1
  • 15
  • 22