以前要验证邮箱,ip, url等常用验证通常都是写了一个正则表达式,今天看到在drupal的includes/common.inc中有这么一个函数filter_var一查竟然是php函数,我以前竟然不知道。而且是从php5.2就开始提供了, 用法如此简单.
验证ip:
filter_var('192.168.0.1', FILTER_VALIDATE_IP, FILTER_FLAG_IPV4);
filter_var('fe80::6e40:8ff:fe99:dee2', FILTER_VALIDATE_IP, FILTER_FLAG_IPV6);
filter_var('192.168.0.1', FILTER_VALIDATE_IP, FILTER_FLAG_IPV4 | FILTER_FLAG_IPV6);
验证邮箱
filter_var('zhouitpro@gmail.com', FILTER_VALIDATE_EMAIL);
URL
filter_var('http://www.5188jxt.com', FILTER_VALIDATE_URL);
数组批量验证:
$data = array(
'id' => 10085,
'url' => 'http://www.baidu.com',
'myip' => '192.168.0.22',
'myfl' => 0.23
);
$filter = array(
'id' => FILTER_VALIDATE_INT,
'url' => FILTER_VALIDATE_URL,
'myip' => FILTER_VALIDATE_IP | FILTER_FLAG_IPV6,
'myfl' => FILTER_VALIDATE_FLOAT
);
$result = filter_var_array($data, $filter);
参考:http://php.net/manual/zh/function.filter-var.php
参数参考: http://php.net/manual/zh/filter.filters.validate.php