0

Need some help with my email validation.. The "[email protected]@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 = "[email protected]@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.";
}
2
  • 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: stackoverflow.com/questions/201323/… Commented May 27, 2015 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. Commented May 27, 2015 at 18:38

1 Answer 1

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 = "[email protected]@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";
}
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.