388   PHP

PHP内置过滤的函数 filter_var, 其中就有包含了邮箱验证的功能,更多资料请查看这里:filter_var

根据需求自己写了个邮箱验证的函数,包括了PHP内置验证方法和自定义正则匹配

代码:

/*

输入:
$VAL_STR,需要验证的字符串
$RE_STR,自定义正则表达式

方法:
默认利用PHP内置方法验证;否则,根据自定义的正则表达式验证

返回:
验证通过返回 true , 否则 false

*/
function validate_email($VAL_STR = null,$RE_STR = null){
	if(empty($VAL_STR)){
		return false;
	}
	if(empty($RE_STR)){
		if(filter_var($VAL_STR,FILTER_VALIDATE_EMAIL) == false){
			return false;
		}else{
			return true;
		}
	}else{
		if(preg_match($RE_STR,$VAL_STR) == 1){
			return true;
		}else{
			return false;
		}
	}
}

$email = 'test@test.com';
$email_163 = 'test163@163.com';
$re_str = '/^[\w]+@163.com$/';
var_dump($email);
echo "\n";
echo "\n---validate_email by default--------\n";
echo "\n-----------$email-----------\n";
var_dump(validate_email($email));
echo "\n";
echo "\n-----------$email_163-----------\n";
var_dump(validate_email($email_163));
echo "\n";
echo "\n---validate_email by $re_str--------\n";
echo "\n-----------$email-----------\n";
var_dump(validate_email($email,$re_str));
echo "\n";
echo "\n-----------$email_163-----------\n";
var_dump(validate_email($email_163,$re_str));

输出内容:

C:\Users\luckybird\Desktop\test>php test.php
string(13) "test@test.com"


---validate_email by default--------

-----------test@test.com-----------
bool(true)


-----------test163@163.com-----------
bool(true)


---validate_email by /^[\w]+@163.com$/--------

-----------test@test.com-----------
bool(false)


-----------test163@163.com-----------
bool(true)




Leave a Reply

Your email address will not be published. Required fields are marked *