函数封装如下,如有疏漏,欢迎指正
/**
* 正则匹配验证字符串
* @params string $str 需要匹配验证的字符串
* @params string $type 匹配类型 手机号:mobile(默认),邮箱:email,网址:url,身份证号:idcard,邮编:post,ip地址:ip
*/
function check_preg($str,$type=""){
if($str){
if($type == '' || $type == 'mobile'){
//验证手机号 默认
return preg_match('#^1[3,8]{1}\d{9}$|^14[5-9]{1}\d{8}$|/^15[\d^4]{1}\d{8}$/|^16[5,6]{1}\d{8}$|^17[0-8]{1}\d{8}$|^19[0,2,6,7,8,9]{1}\d{8}$#', $str) ? true : false;
}else if($type == 'email'){
//验证邮箱
return preg_match('#[a-z0-9&\-_.]+@[\w\-_]+([\w\-.]+)?\.[\w\-]+#is', $str) ? true : false;
}else if($type == 'url'){
//验证url
return preg_match('#(http|https|ftp|ftps)://([\w-]+\.)+[\w-]+(/[\w-./?%&=]*)?#i', $str) ? true : false;
}else if($type == 'idcard'){
//验证身份证号
return preg_match('#^([\d]{17}[xX\d])$#', $str) ? true : false;
}else if($type == 'post'){
//验证邮编
return preg_match('#^[0-9][\d]{5}$#', $str) ? true : false;
}else if($type == 'ip'){
//验证ip地址
if(preg_match('#^\d{1,3}\.\d{1,3}\.\d{1,3}\.\d{1,3}$#', $str)){
$ipArray = explode('.', $str);
//真实的ip地址每个数字不能大于255(0-255)
return $ipArray[0]<=255 && $ipArray[1]<=255 && $ipArray[2]<=255 && $ipArray[3]<=255 ? true : false;
}else{
return false;
}
}else{
return false;
}
}else{
return false;
}
}