问题
i have a textarea:
<form action="index.php" method="post">
<textarea name="test" rows="20" cols="20"></textarea>
<input type="submit" />
</form>
i want to type 195.2.2.13/16 and PHP should give me a list like that:
195.2.2.13
195.2.2.14
195.2.2.15
195.2.2.16
how can i do it with PHP?
回答1:
I noticed that the code posted originally was fine for two decimal points but just incase you need to use 3 the below should work fine.
$input = "195.2.2.13/100";
function ipRange( $input ) {
$input = explode( "/", $input );
$numerator = substr( strrchr( $input[0], "." ), 1, 3 );
$denominator = $input[1];
$num = strlen( $numerator );
$range = substr( $input[0], 0, -$num );
while ( $numerator <= $denominator ) {
echo $range.$numerator."<br />\n\r";
$numerator++;
}
}
// Call function
ipRange($input);
回答2:
You could do this with ip2long.
Convert your string to an int, get the min and max IPs, iterate between them and render them back with long2ip.
回答3:
$parts = explode('/', $_POST['name']);
$ip = $parts[0];
$max = $parts[1];
$octets = explode('.', $ip);
$start = $octets[3];
$ips = array();
for ($i = $start; $i <= $max; $i++) {
if ($i > 254) {
break;
}
$ips[] = $octets[0] . '.' . $octets[1] . '.' . $octets[2] . '.' . $i;
}
来源:https://stackoverflow.com/questions/7698596/exploding-given-ip-range-with-the-php