Page 1 of 1
Validating email with regular expressions(preg_match)
Posted: Tue Jul 19, 2011 3:33 pm
by borisboris
I'm a PHP newbie. I have the following code but cannot get it to work, any ideas on how to make this code work:
$email = "
myemail@yahoo.com";
$good_email = ([a-zA-Z0-9]+@[a-zA-Z0-9_-]+\.[a-zA-Z0-9_-]+)+";
if (preg_match(/"$good_email"/, $email)) {
echo $email." is a valid email address.<br>";
}
Re: Validating email with regular expressions(preg_match)
Posted: Tue Jul 19, 2011 3:50 pm
by sspatel82
Actually you don't need regular expression to validate email....thanks to PHP functionality. Here is magic.
Code: Select all
if (filter_var('test+email@fexample.com', FILTER_VALIDATE_EMAIL)) {
echo "Your email is ok.";
} else {
echo "Wrong email address format.";
}
Then also if you are picky for regular expression then here is the solution......
Code: Select all
$email = "test@example.com";
if (preg_match('/^[^0-9][a-zA-Z0-9_]+([.][a-zA-Z0-9_]+)*[@][a-zA-Z0-9_]+([.][a-zA-Z0-9_]+)*[.][a-zA-Z]{2,4}$/',$email)) {
echo "Your email is ok.";
} else {
echo "Wrong email address format";
}
---------------
Sanket Patel
Re: Validating email with regular expressions(preg_match)
Posted: Tue Jul 19, 2011 8:11 pm
by McInfo
sspatel82 wrote:Code: Select all
'/^[^0-9][a-zA-Z0-9_]+([.][a-zA-Z0-9_]+)*[@][a-zA-Z0-9_]+([.][a-zA-Z0-9_]+)*[.][a-zA-Z]{2,4}$/'
That pattern fails on some valid email addresses (even the one in your first example which is declared valid by filter_var()). Do a web search for "rfc email address format".
Re: Validating email with regular expressions(preg_match)
Posted: Tue Jul 19, 2011 10:31 pm
by sspatel82
Ok, I know because in market there are lots of solutions to validate email, but no one is full proof...
Here is nice article, check this topic in that ...
The Official Standard: RFC 2822
http://www.regular-expressions.info/email.html