把开发中常用的一些正则验证整理了一下,在这里分享一下。本文章也会不断更新,给自己留个底。
/**
* @method 邮箱验证
* @param $email
* @return bool
*/
function validEmail($email)
{
$isValid = true;
$atIndex = strrpos($email, "@");
if (is_bool($atIndex) && !$atIndex) {
$isValid = false;
} else {
$domain = substr($email, $atIndex + 1);
$local = substr($email, 0, $atIndex);
$localLen = strlen($local);
$domainLen = strlen($domain);
if ($localLen < 1 || $localLen > 64) {
$isValid = false;
} else if ($domainLen < 1 || $domainLen > 255) {
$isValid = false;
} else if ($local[0] == '.' || $local[$localLen - 1] == '.') {
$isValid = false;
} else if (preg_match('/\\.\\./', $local)) {
$isValid = false;
} else if (!preg_match('/^[A-Za-z0-9\\-\\.]+$/', $domain)) {
$isValid = false;
} else if (preg_match('/\\.\\./', $domain)) {
$isValid = false;
} else if (!preg_match('/^(\\\\.|[A-Za-z0-9!#%&`_=\\/$\'*+?^{}|~.-])+$/', str_replace("\\\\", "", $local))) {
if (!preg_match('/^"(\\\\"|[^"])+"$/', str_replace("\\\\", "", $local))) {
$isValid = false;
}
}
if ($isValid && !(checkdnsrr($domain, "MX") || checkdnsrr($domain, "A"))) {
$isValid = false;
}
}
return $isValid;
}
/**
* @method 验证有效邮编
* @param $val 邮政编码
* @return bool
*/
function validZipCode($val)
{
return !!preg_match('/^[0-9]\d{5}$/', $val);
}
/**
* @method 验证有效手机号
* @param $val 11位手机号
* @return bool
*/
function validMobile($val)
{
return !!preg_match('/^1(3|4|5|7|8|6|9)[0-9]\d{8}$/', $val);
}
/**
* @method 验证有效身份证号
* @param $val
* @return bool
*/
function validIdCard($val)
{
!!preg_match('/^\d{17}[0-9xX]$/', $val);//基本格式校验
$parsed = date_parse(substr($val, 6, 8));
if (!(isset($parsed['warning_count'])
&& $parsed['warning_count'] == 0)
) { //年月日位校验
return false;
}
$base = substr($val, 0, 17);
$factor = [7, 9, 10, 5, 8, 4, 2, 1, 6, 3, 7, 9, 10, 5, 8, 4, 2];
$tokens = ['1', '0', 'X', '9', '8', '7', '6', '5', '4', '3', '2'];
$checkSum = 0;
for ($i = 0; $i < 17; $i++) {
$checkSum += intval(substr($base, $i, 1)) * $factor[$i];
}
$mod = $checkSum % 11;
$token = $tokens[$mod];
$lastChar = strtoupper(substr($val, 17, 1));
return ($lastChar === $token); //最后一位校验位校验
}
/**
* @method 验证有效正整数
* @param $val
* @return bool
*/
function validNumber($val)
{
return !!(is_numeric($val) && is_int($val + 0) && ($val + 0) >= 0);
}