正则
正则表达式中的特殊字符
限定符
常用匹配简化操作
[0-9] \d 数字
[^0-9] \D 非数字
[A-Za-z0-9_] \w 匹配是下划线和数字,字母
[^A-Za-z0-9_] \W 匹配不是下划线和数字,字母
. 匹配所有
[xyz] 匹配字母xyz
[^xyz] 不匹配字母xyz
x|y 匹配
实际操作
//1.匹配手机号码 $str1 = '12345678901'; $str2 = '123456789sdf'; $str3 = '12345678912p'; echo "<h1>匹配手机</h1>"; preg_match_all("/^1\d{10}$/", $str1, $t1); print_r($t1); echo '<hr>'; preg_match_all("/^1\d{10}$/", $str2, $t2); print_r($t2); echo '<hr>'; preg_match_all("/^1\d{10}$/", $str3, $t3); print_r($t3);
echo '<h1>匹配邮箱</h1>'; $str1 = "981596276@qq.com"; $str2 = "981596276@qqcom"; $str3 = "981596276qq.com"; $preg = "/^(\d+)@(\w+)$/"; preg_match_all($preg, $str1, $t1); print_r($t1); echo '<hr>'; preg_match_all($preg, $str2, $t2); print_r($t2); echo '<hr>'; preg_match_all($preg, $str3, $t3); print_r($t3);
echo '<h1>省+市+具体地址查分</h1>'; $str = "江西省九江市XXXXXXXXXXXX"; $preg = "/^(.+省)(.+市)(.+)/"; preg_match_all($preg, $str, $x); print_r($x);
echo '<h1>匹配网址</h1>'; $str1 = "http://www.baidu.com"; $str2 = "https://www.google.com"; $str3 = "www.xina.com"; $str4 = "www.xinsdfsdfsdf"; $preg = "/^((http|https):\/\/)?[a-z]{3}\.[a-z]+\.[a-z]+$/"; preg_match_all($preg, $str1, $t1); print_r($t1); echo '<hr>'; preg_match_all($preg, $str2, $t2); print_r($t2); echo '<hr>'; preg_match_all($preg, $str3, $t3); print_r($t3); echo '<hr>'; preg_match_all($preg, $str4, $t4); print_r($t4);