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   = "local@test.com";
$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!

ipalaus
  • 2,253
  • 4
  • 27
  • 42

2 Answers2

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.

SirDarius
  • 41,440
  • 8
  • 86
  • 100
  • 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 `\.` – mario Jan 04 '11 at 16:50
  • 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. – SirDarius Jan 04 '11 at 17:03
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 = "local@root.ws";

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

Hope it helps!