我不相信正则表达式在这种情况下是必要的甚至是有用的,尤其是 PHP 有filter_var()
:
function isValid($ranges) {
// remove all spaces
$ranges = str_replace(' ', '', $ranges);
// iterate over individual ranges and IP addresses
foreach(explode(';', $ranges) as $range) {
// single address
if(strpos($range, '-') === false) {
if(!filter_var($range, FILTER_VALIDATE_IP)) {
return false;
}
}
// range
else {
$addresses = explode('-', $range, 3);
if(count($addresses) != 2) {
return false;
}
if(!filter_var($addresses[0], FILTER_VALIDATE_IP) || !filter_var($addresses[1], FILTER_VALIDATE_IP)) {
return false;
}
}
}
return true;
}
$tests = array(
'74.122.31.233; 76.233.12.222 - 80.788.888.111; 72.203.44.209',
'74.122.31.233; 76.233.12.222; 72.203.44.209',
'74.122.31.233 - 76.233.12.222; 72.203.44.209',
'74.122.31.233-76.233.12.222; 72.203.44.209',
'74.122.31.233-76.233.12.222;72.203.44.209');
foreach($tests as $test) {
echo $test;
echo isValid($test) ? ' is valid' : ' is invalid';
echo "\n";
}
输出:
74.122.31.233; 76.233.12.222 - 80.788.888.111; 72.203.44.209 is invalid // 80.788.888.111 is an invalid IP address
74.122.31.233; 76.233.12.222; 72.203.44.209 is valid
74.122.31.233 - 76.233.12.222; 72.203.44.209 is valid
74.122.31.233-76.233.12.222; 72.203.44.209 is valid
74.122.31.233-76.233.12.222;72.203.44.209 is valid