0

I can't get working a preg_match() in PHP to validate an e-mail address. I've tested the RegEx expression that I've found on Internet with the http://www.regexer.com tool and works fine with the same input I'm using on my PHP application.

RegEx expression:

^([a-z0-9\+_\-]+)(\.[a-z0-9\+_\-]+)*@([a-z0-9\-]+\.)+[a-z]{2,6}$

Regexer: http://regexr.com?2sr2a

And I'm applying it like this in PHP:

$email   = "[email protected]";
$pattern = "/^([a-z0-9\+_\-]+)(\.[a-z0-9\+_\-]+)*@([a-z0-9\-]+\.)+[a-z]{2,6}$/ix";

if (false == preg_match($pattern, $email))
    echo "false";

And of course, I get a false with this e-mail and others that I've tested. The expression I think is well formed because on regexer I can test and it works. What I'm applying incorrectly?

Thank you in advance!

7
  • Cannot reproduce. The regex is ok. Commented Jan 4, 2011 at 16:43
  • The example code works fine for me. Commented Jan 4, 2011 at 16:44
  • Works for me: ideone.com/IkQo2 Commented Jan 4, 2011 at 16:44
  • @SirDarius: Thank you. That was the problem! :) Commented Jan 4, 2011 at 16:45
  • 1
    Gazillion duplicates - use PHP's native filter_var instead of a regex Commented Jan 4, 2011 at 16:45

2 Answers 2

1

Backslash characters need to be properly escaped by doubling them like this:

$pattern = "/^([a-z0-9\\+_\\-]+)(\\.[a-z0-9\\+_\\-]+)*@([a-z0-9\\-]+\\.)+[a-z]{2,6}$/ix";

Using this pattern, preg_match correctly returns 1.

Sign up to request clarification or add additional context in comments.

2 Comments

They don't normally. Backslashes are only stripped when they preceed another backslash, double quote, $, octal literals, or one of the ascii escapes \r \n \t. print "\." will print \.
Although it's not mandatory to escape backslashes, it is highly recommended to do so in double-quoted strings, especially if you might accidentally insert a character causing the creation of a valid escape sequence.
0

I am not sure what is wrong in your code but here you have a fully functional php function for checking an email address:

function is_validemail($email) 
{
     return preg_match('/^[\w.-]+@([\w.-]+\.)+[a-z]{2,6}$/is', $email);
}

$email = "[email protected]";

if(is_validemail($email)) { echo ("email validated"); } else { echo ("invalid email given"); }

Hope it helps!

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.