函数封装如下,如有疏漏,欢迎指正
/** * 正则匹配验证字符串 * @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('#^13[\d]{9}$|^14[5,7,9]{1}\d{8}$|^15[^4]{1}\d{8}$|^166[\d]{8}$|^17[0,1,3,5,6,7,8]{1}\d{8}$|^18[\d]{9}$|^19[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; } }
【版权声明】感谢转载,转载请注明出处。 李维山博客http://msllws.top