正则表达验证常用的手机号和邮箱地址(PHP)

版权声明:本文为博主原创文章,未经博主允许不得转载。 https://blog.csdn.net/xuyawei_xyw/article/details/81070548

      正则表达式是对字符串操作的一种逻辑公式,正则表达的验证是在实际开发中作为比较重要的一步,用好了正则表达,可以减少许多代码量以及逻辑判断。下面写下在开发中常用的邮箱和手机号验证:

邮箱地址和手机号码的提交:

validate.html

<!DOCTYPE html>
<html>
<head>
    <title>正则表达验证</title>
</head>
<body>
    <meta charset="utf-8">
    <head>
	<h5>正则表达式验证邮箱和手机号</h5>
    </head>
    <form action="validate.php" method="post">
	邮箱地址:<input type="text" name="email"><br /><br />
	手机号码:<input type="text" name="mobile_phone"><br/><br/>
	<input type="submit" value="提交">
    </form>
</body>
</html>

邮箱地址和手机号码的接收并验证的方法剥离:

<?php
header("Content-Type:text/html;charset=utf-8");
$email = $_REQUEST['email'];
$mobile_phone = $_REQUEST['mobile_phone'];
if(!is_email($email))
{
    die("邮箱地址不正确");
}
if(!is_mobile_phone($mobile_phone))
{
    die("手机号格式不正确");
}
if(is_email($email) && is_mobile_phone($mobile_phone)){
    die("验证通过,请进行下一步操作");
}

/**
 * 验证输入的邮件地址是否合法
 * @access  public
 * @param   string      $email      需要验证的邮件地址
 * @return bool
 */
function is_email($email)
{
    $chars = "/^([a-z0-9+_]|\\-|\\.)+@(([a-z0-9_]|\\-)+\\.)+[a-z]{2,6}\$/i";
    if (strpos($email, '@') !== false && strpos($email, '.') !== false)
    {
        if (preg_match($chars, $email))
	{
	    return true;
	}else{
	    return false;
	}
    }else{
	return false;
    }
}
/**
 * 验证输入的手机号码是否合法
 * @access public
 * @param string $mobile_phone
 * 需要验证的手机号码
 * @return bool
 */
function is_mobile_phone ($mobile_phone)
{
    $chars = "/^13[0-9]{1}[0-9]{8}$|15[0-9]{1}[0-9]{8}$|18[0-9]{1}[0-9]{8}$|17[0-9]{1}[0-9]{8}$/";
    if(preg_match($chars, $mobile_phone))
    {
	return true;
    }
    return false;
}

截图显示:

输出:手机号格式不正确

输出:验证通过,请进行下一步操作

猜你喜欢

转载自blog.csdn.net/xuyawei_xyw/article/details/81070548
今日推荐