我在尝试“打印”PHP函数以将IP地址范围转换为CIDR格式时遇到问题,以下是IP2Location.com发布的函数:
https://www.ip2location.com/tutorials/how-to-convert-ip-address-range-into-cidr
function iprange2cidr($ipStart, $ipEnd){
if (is_string($ipStart) || is_string($ipEnd)){
$start = ip2long($ipStart);
$end = ip2long($ipEnd);
}
else{
$start = $ipStart;
$end = $ipEnd;
}
$result = array();
while($end >= $start){
$maxSize = 32;
while ($maxSize > 0){
$mask = hexdec(iMask($maxSize - 1));
$maskBase = $start & $mask;
if($maskBase != $start) break;
$maxSize--;
}
$x = log($end - $start + 1)/log(2);
$maxDiff = floor(32 - floor($x));
if($maxSize < $maxDiff){
$maxSize = $maxDiff;
}
$ip = long2ip($start);
array_push($result, "$ip/$maxSize");
$start += pow(2, (32-$maxSize));
}
return $result;
}
function iMask($s){
return base_convert((pow(2, 32) - pow(2, (32-$s))), 10, 16);
}
(注:已将'echo‘更正为'return’结果)
我尝试了所有建议的方法,将数组和数组的值“馈送”给函数,以及“回显”或“打印”结果数组,但我得到的都是单词“$ipStart”。
例如,在定义函数后,我尝试:
$ipStart = '8.8.8.8';
$ipEnd = '8.8.8.254';
echo iprange2cidr($ipStart, $ipEnd);
..。我为这个新手问题道歉,我是一个PHP新手。我只是不确定如何使用这个函数。任何关于我做错了什么的指导都将不胜感激!我的服务器使用PHP7.1。谢谢。
发布于 2018-06-17 22:37:16
让我们返回$result
。
function iprange2cidr($ipStart, $ipEnd){
....
return $result;
}
然后,让我们在回显之前将其转换为字符串:
$ipStart = '8.8.8.8';
$ipEnd = '8.8.8.254';
$range = iprange2cidr($ipStart, $ipEnd);
echo implode("\n",$range);
发布于 2018-06-17 22:46:56
您可以使用print_r($result);
获得人类可读的输出。
有关详细信息,请参阅doc。
发布于 2018-06-17 22:53:31
使用函数的正确方法是返回如下所示的值
function iprange2cidr($ipStart, $ipEnd){
....
return $result;}
然后调用像$returnedVale = iprange2cidr($ipStart,$ipEnd)这样的函数;
$returnedVale = iprange2cidr($ipStart, $ipEnd);
echo"<pre>";print_r($returnedVale);echo"</pre>";
https://stackoverflow.com/questions/50897590
复制相似问题