首页> 基础笔记 >PHP基础学习 >PHP正则 PHP正则

PHP正则函数preg_match()实现简单的表单验证

作者:小萝卜 2019-08-21 浏览 851

简介PHP正则函数preg_match()实现简单的表单验证

html:
<!DOCTYPE html>
<html>
    <head>
        <meta charset="utf-8"/>
        <title>使用正则实现表单数据验证</title>
    </head>
    <body>
        <h3>正则验证实例</h3>
        <form action="3.php" method="post">
         账号:<input type="text" name="uname"/> 6-18大小字母、数字或下划线<br/><br/>
         密码:<input type="password" name="upass"/> 至少6位字母和数字及其他混合<br/><br/>
         年龄:<input type="text" name="age"/><br/><br/>
         邮箱:<input type="text" name="email"/><br/><br/>
         <input type="submit" value="提交"/>
        </form>
    </body>
</html>
preg_match()验证代码:
<?php
header("Content-Type:text/html;charset=utf-8");
//使用正则验证表达数据

//获取信息
$name = $_POST['uname'];
$pass = $_POST['upass'];
$age  = $_POST['age'];
$mail = $_POST['email'];

//执行一个个正则验证

if(!preg_match("/^\w{6,18}$/",$name)){
    die("你的账号格式错误!");
}
if(!preg_match("/^.{6,}$/",$pass)){
    die("你的密码必须在6位及以上");
}
if(!preg_match("/[0-9]/",$pass)){
    die("你的密码必须有0-9的数字");
}
if(!preg_match("/[a-zA-Z]/",$pass)){
    die("你的密码必须有大小写字母");
}
//年龄判断
if(!preg_match("/^[0-9]{2}$/",$age) || $age<18){
    die("年龄信息不合法!");
}

//email判断
if(!preg_match("/^\w+@\w+(\.\w+){1,2}$/",$mail)){
    die("Email信息不合法!");
}

//输出数据
echo "你的账号:".$name."<br/>";
echo "你的密码:".$pass."<br/>";
echo "你的年龄:".$age."<br/>";
echo "你的邮箱:".$mail."<br/>";
 

很赞哦! (0)

文章评论

    高端网站建设