猫哥写代码时候经常会遇到各种需要判断的:
- 判断是否数字;
- 判断是否字符串;
- 判断是否合法email;
- 判断是否IPv4地址;
- ......
从前总会傻傻地写各种正则表达式,虽然正则水平有所提高,但是效率低吖~
直到有一天猫哥发现了filter_var这个强大的工具!之前的猫哥哭晕在厕所...
官网文档:http://php.net/manual/en/function.filter-var.php
来看一系列栗子:
<?php # coding: utf-8
$ip = '1.2.3.4';
if(filter_var($ip, FILTER_VALIDATE_IP)) {
echo $ip." is valid IP <br>";
} else {
echo $ip." is not valid IP. <br>";
}
$ip = '311.2.3.4';
//判断是否是合法的IPv4 IP地址
if(filter_var($ip, FILTER_VALIDATE_IP, FILTER_FLAG_IPV4)) {
echo "Second paragraph...<br>";
echo $ip." is valid IP <br>";
} else {
echo $ip." is not valid IP <br>";
}
$ip = '10.1.1.1'; //192.168.1.1 这类的一样...
//判断是否是合法的公共IPv4地址
if(filter_var($ip, FILTER_VALIDATE_IP, FILTER_FLAG_IPV4 | FILTER_FLAG_NO_PRIV_RANGE)) {
echo $ip." is public IPv4 <br>";
} else {
echo $ip." is not public IPv4 <br>";
}
$ip = 'FF01::101';
//判断是否是合法的IPv6地址
if(filter_var($ip, FILTER_VALIDATE_IP, FILTER_FLAG_NO_RES_RANGE)) {
echo $ip." is valid IPv6 <br>";
} else {
echo $ip." is not valid IPv6 <br>";
}
$email = "a@bc.cn";
//判断是否是public IPv4 IP或者是合法的Public IPv6 IP地址
if(filter_var($email, FILTER_VALIDATE_EMAIL)) {
echo $email." is a valid email. <br>";
} else {
echo $email." is not valid email. <br>";
}
$url = "http://blog.csdn.net/972301/article/details/50654449";
if(filter_var($url, FILTER_VALIDATE_URL)) {
echo $url." is a valid url. <br>";
} else {
echo $url." is not valid url. <br>";
}
$mac = "00:11:22:EE:ff:aa";
if(filter_var($mac, FILTER_VALIDATE_MAC)) {
echo $mac." is a valid mac address. <br>";
} else {
echo $mac." is not valid mac address. <br>";
}
结果:
1.2.3.4 is valid IP
311.2.3.4 is not valid IP
10.1.1.1 is not public IPv4
FF01::101 is valid IPv6
a@bc.cn is a valid email.
http://blog.csdn.net/972301/article/details/50654449 is a valid url.
00:11:22:EE:ff:aa is a valid mac address.
当然,更详细的解释和filters,还是要看看官网: http://php.net/manual/en/filter.filters.php
编后按
猫哥曰:正则虽好,效率第一,为了进度,你懂的~