PHP常用正则表达式整理,验证手机号、邮箱、用户名、密码等

手机号验证

<?php
//正则表达式
$tel = "13012345678";
//上面部分判断长度是不是11位
if (strlen($tel) == "11") {
  /*接下来的正则表达式以1开头随后跟着任意的9为数字*/
  if (!preg_match("/^1[3456789]\d{9}$/", $tel)) {
  	echo "手机号不正确";
  }   
} else {
  echo "长度必须是11位";
}
?> 

邮箱验证

<?php
if (!preg_match('/\w+([-+.]\w+)*@\w+([-.]\w+)*\.\w+([-.]\w+)*/', $email)) {
	echo "邮箱不合法";
}

//使用 FILTER_VALIDATE_EMAIL 过滤器
if (filter_var($email, FILTER_VALIDATE_EMAIL)) {
    $emailMsg = "正确邮箱格式";
}
?>

验证url

$url = strtolower(trim($url ));
if(empty($url )) {
	echo "url格式不正确";
}
$match = '/^(http:\/\/)?(https:\/\/)?([\w\d\-]+\.)+[\w\-]+(\/[\d\w\-.\/?%&=]*)?$/';
if (!preg_match($match, $url)) {
	echo "url格式不正确";
}

用户名验证

//6-20位字符,必须以字母开头,只能包含数字、字母、下划线,不区分大小写
$match = '/^[a-zA-Z_][a-zA-Z0-9-_]{5,19}$';
if (!preg_match($match, $username)) {
	echo "用户名格式不正确";
}

密码验证

//6-16位字符,需包括数字与英文字母
$match = '/^(?![0-9]+$)(?![a-z]+$)(?![A-Z]+$)(?!([^(0-9a-zA-Z)])+$).{6,16}$/';
if (!preg_match($match, $pwd)) {
	echo "密码格式不正确";
}

IP验证

$match = '/^(25[0-5]|2[0-4][0-9]|[0-1]{1}[0-9]{2}|[1-9]{1}[0-9]{1}|[1-9])\.(25[0-5]|2[0-4][0-9]|[0-1]{1}[0-9]{2}|[1-9]{1}[0-9]{1}|[1-9]|0)\.(25[0-5]|2[0-4][0-9]|[0-1]{1}[0-9]{2}|[1-9]{1}[0-9]{1}|[1-9]|0)\.(25[0-5]|2[0-4][0-9]|[0-1]{1}[0-9]{2}|[1-9]{1}[0-9]{1}|[0-9])$/';
if (!preg_match($match, $ip)) {
	echo "IP格式不正确";
}

身份证号验证

$match = '/^\d{6}((1[89])|(2\d))\d{2}((0\d)|(1[0-2]))((3[01])|([0-2]\d))\d{3}(\d|X)$/i';
if (!preg_match($match, $idcard)) {
	echo "身份证号不正确";
}

电话号码验证

$match = '/^0[0-9]{2,3}[-]?\d{7,8}$/';
if (!preg_match($match, $phone)) {
	echo "电话号码不正确";
}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值