正则表达式来判断是否是合法的IP
if ( preg_match( '#^(([1-9]?\d|1\d\d|25[0-5]|2[0-4]\d)\.){3}([1-9]?\d|1\d\d|25[0-5]|2[0-4]\d)$#', $ip ) ) { echo "it's valid"; }else{ echo "it's not valid"; }
php自带函数来判断是否是合法的IP
// 判断是否是合法IP if(filter_var($ip, FILTER_VALIDATE_IP)) { echo "it's valid"; }else { echo "it's not valid"; } // 判断是否是合法的IPv4 IP地址 if(filter_var($ip, FILTER_VALIDATE_IP, FILTER_FLAG_IPV4)) { echo "it's valid"; }else { echo "it's not valid"; } // 判断是否是合法的公共IPv4地址,192.168.1.1这类的私有IP地址将会排除在外 if(filter_var($ip, FILTER_VALIDATE_IP, FILTER_FLAG_IPV4 | FILTER_FLAG_NO_PRIV_RANGE)) { echo "it's valid"; }else { echo "it's not valid"; } // 判断是否是合法的IPv6地址 if(filter_var($ip, FILTER_VALIDATE_IP, FILTER_FLAG_NO_RES_RANGE)) { echo "it's valid"; }else { echo "it's not valid"; } // 判断是否是public IPv4 IP或者是合法的Public IPv6 IP地址 if(filter_var($ip, FILTER_VALIDATE_IP, FILTER_FLAG_NO_PRIV_RANGE | FILTER_FLAG_NO_RES_RANGE)) { echo "it's valid"; }else { echo "it's not valid"; }