php 检测IP(包含ip段)

来源:互联网 发布:windows loader好用吗 编辑:程序博客网 时间:2024/05/22 23:58

除了正常IP检测之外, 255.255.255.x 代表的ip段也是合法的

IP 正则:   /\b((25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)(\.|$)){4}\b/


实例代码如下:

        if (isset($data['access_ip']) && $data['access_ip']) {            $ip_list = explode(PHP_EOL, $data['access_ip']);            // check ip one by one            $ip_list = array_map(function($ip_str){                $ip_str = trim($ip_str);                // normal ip                $ip_validate_result= filter_var($ip_str, FILTER_VALIDATE_IP);                if ($ip_validate_result) {                    return $ip_str;                }                // match ip eg: 172.18.19.x                $regex_ip = '/\b((25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)(\.|$)){3}x$/';                $ip_reg_result = preg_match($regex_ip, $ip_str, $matches);                if ($ip_reg_result) {                    return $ip_str;                }                throw new \Exception('IP白名单输入不合法');            },$ip_list);            $data['access_ip'] = $ip_list;        } else {            $data['access_ip'] = '';        }        return $data;    }