正则表达式也称为模式表达式,自身具有一套非常完整的、可以编写模式的语法体系,提供了一种灵活且直观的字符串处理方法。正则表达式通过构建具有特定规则的模式,与输入的字符串信息比较,从而实现字符串的匹配、查找、替换及分割等操作。
这个程序实现的是用正则表达式实现登录验证的一个Demo
<1>:
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
|
<?php if (isset( $_POST [ "sub" ])){ $text = $_POST [ "text" ]; $patten = '^[0-9]*$' ; if (!preg_match( $patten , $text , $x )){ echo "<script>alert('用户没有输入数字');</script>" ; } else { if ( $x <1){ $y = $x ; echo "y=" . $y . "<br>" ; } else if ( $x <10){ $y =2* $x -1; echo "y=" . $y . "<br>" ; } else { $y =3* $x -11; echo "y=" . $y . "<br>" ; } } ?> <html> <head> </head> <body> <form method= 'post' > 请输入信息:<input type= "text" name= "text" > <input type= "submit" name= "sub" value= "提交" > </form> </body> </html> |
<2>:
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
|
<html> <head> </head> <body> <form method= 'post' > 注册账号:<input type= "text" name= "aNum" ><br> 登录密码:<input type= "password" name= "pwd" ><br> 重复密码:<input type= "password" name= "rPwd" ><br> 邮箱地址:<input type= "text" name= "email" ><br> 手机号码:<input type= "text" name= "tel" ><br> <input type= "submit" name= "sub" value= "注册" > <?php if (isset( $_POST [ "sub" ])){ $aNum = $_POST [ "aNum" ]; $pwd = $_POST [ "pwd" ]; $rPwd = $_POST [ "rPwd" ]; $email = $_POST [ "email" ]; $tel = $_POST [ "tel" ]; $patten1 = "^\w+(\.[\w-]+)*@[\w-]+(\.[\w-]+)+$" ; //验证邮箱 $patten2 = "[0-9]{11}" ; //11位数字组成,验证手机号码 $patten3 = "[a-zA-Z_\x7f-\xff][a-zA-Z0-9_\x7f-\xff]*" //验证账号 if (!preg_match( $patten3 , $aNum )){ echo "<script>alert('账号格式不对');</script>" ; } else { if ( $pwd .length<6){ echo "<script>alert('密码格式不对');</script>" ; } else { if (!preg_match( $patten , $email )){ echo "<script>alert('email格式不正确');</script>" ; } else { if (!preg_match( $patten2 , $tel )){ echo "<script>alert('手机号码格式不正确');</script>" ; } else { if ( strlen ( $pwd )!= strlen ( $rPwd )){ echo "<script>alert('两次密码不一致');</script>" ; } else { echo "用户您好!您的账号为:" . $aNum . ",密码为:" . $pwd . ",邮箱为:" . $email . ",手机号码为:" . $tel ; } } } } } ?> </form> </body> </html> |