0

Need some help with my email validation.. The "very.unusual.@.unusual.com@example.com" should be a valid email. But the php is showing that it is invalid. Any help would be awesome

You can execute the code here: http://sandbox.onlinephpfunctions.com/

    $unusual = "very.unusual.@.unusual.com@example.com";
$regex = "^[a-z0-9,!#\$%&'\*\+/=\?\^_`\{\|}~-]+(\.[a-z0-9,!#\$%&'\*\+/=\?\^_`\{\|}~-]+)*@[a-z0-9-]+(\.[a-z0-9-]+)*\.([a-z]{2,})$"; 
$normal = "^[a-z0-9_\+-]+(\.[a-z0-9_\+-]+)*@[a-z0-9-]+(\.[a-z0-9-]+)*\.([a-z]{2,4})$";
$domain = "[a-z0-9-]+(\.[a-z0-9-]+)*\.([a-z]{2,})$"; 

$dom = strrchr($unusual,"@");

//find length of the needle
$len = strlen($dom);

//find postion
$position = strpos($unusual,$dom);

//cut the string
$begin = substr("$unusual",0,$position);


$end = substr("$unusual",$position+1);

//display it
echo"$begin\n"; 
echo "$end";

if ( eregi( $normal, $begin ) ) {
     echo $begin . " is a valid local. We can accept it.";
} else { 
     echo $begin . " is an invalid local. Please try again.";
} 
if ( eregi( $domain, $end ) ) {
     echo $end . " is a valid domain. We can accept it.";
} else { 
     echo $end . " is an invalid domain. Please try again.";
}
kamal
  • 195
  • 2
  • 9
  • 2
    This might be good reading - honestly, at some point, just make sure it looks *something* like an email address, and if it really matters, probably just send a validation email: http://stackoverflow.com/questions/201323/using-a-regular-expression-to-validate-an-email-address – Mike May 27 '15 at 17:53
  • ...This is a _horrible_ idea. Generally, if it has an `@` and a valid-looking domain after that, it's valid. Constructing a real regex to find valid emails just means that you'll have slightly fewer times that your "make sure this _valid_ email is a _real_ email" script runs. – Nic May 27 '15 at 18:38

1 Answers1

3

I'm not a big fan of using regex when there are other functions PHP offers that are easier to read and understand. Try this:

$email = "very.unusual.@.unusual.com@example.com";

if ( ! filter_var($email, FILTER_VALIDATE_EMAIL) === false) 
{
    echo "$email is a valid email address";
} 
else 
{
    echo "$email is not a valid email address";
}
diggersworld
  • 12,770
  • 24
  • 84
  • 119