Validating email with regular expressions(preg_match)

PHP programming forum. Ask questions or help people concerning PHP code. Don't understand a function? Need help implementing a class? Don't understand a class? Here is where to ask. Remember to do your homework!

Moderator: General Moderators

Post Reply
borisboris
Forum Newbie
Posts: 1
Joined: Tue Jul 19, 2011 3:24 pm

Validating email with regular expressions(preg_match)

Post 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>";
}
sspatel82
Forum Newbie
Posts: 9
Joined: Tue Jul 19, 2011 10:52 am

Re: Validating email with regular expressions(preg_match)

Post 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
User avatar
McInfo
DevNet Resident
Posts: 1532
Joined: Wed Apr 01, 2009 1:31 pm

Re: Validating email with regular expressions(preg_match)

Post 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".
sspatel82
Forum Newbie
Posts: 9
Joined: Tue Jul 19, 2011 10:52 am

Re: Validating email with regular expressions(preg_match)

Post 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
Post Reply