首页/Home PHP Basics Email Validation Checking With Regular Expression

Email Validation Checking With Regular Expression

PrintE-mail
Sunday, 03 February 2008 17:00  

Email validation check can be long or short. Here I will just illustrate a short form.
Also, this code can check ip based email address.

 

Let's have a look at the code:

/**
* Check whether an email address is valid or not (Using PHP)
*
* @param string $email
* @return true or false
* @author Shelley Shyan
* @copyright http://phparch.cn (Prefessional PHP Architecture)
*/
function isValidEmail($email)
{
$subIP = '(25[0-5]|2[0-4]\d|1\d\d|[1-9]\d|\d)';
$validUser = '[\w]+([\.-][\w]+)*';
$validStrDomain = '(([\w]+(-[\w]+)*)+\.)+[a-z]{2,6}';
$validIpAddr = "$subIP([\.]$subIP){3}";

$strPattern = "/^$validUser@$validStrDomain$/i";
$ipPattern = "/^$validUser@$validIpAddr$/i";


if (
preg_match($strPattern, $email) || preg_match($ipPattern, $email)) {
return
true;
} else {
return
false;
}
}

$subIP checks whether the IP address is between 0-255.

So the function can check email like:

user_name@a-example.com
user.name@example.co.uk
user-name@example.mobi
user_007@123.234.2.0

Most of the email validation checking PHP pages talk about only string domain. You know, of course, IP address is also no problem.

Hope these code can give you some help.