我对这种情况有疑问,如何通过Array存储字符串? 这是我的代码
<?php
$octets = array($_POST["oct1"],$_POST["oct2"],$_POST["oct3"],$_POST["oct4"]);
$octlenfnl = count($octets) - 1;
$binoctstr = 0 ;
if($_POST["oct1"] <= 255 && $_POST["oct1"] <= 255 && $_POST["oct1"] <= 255 && $_POST["oct1"] <= 255)
{
for($i=0;$i<=$octlenfnl;$i++){
echo str_pad(decbin($octets[$i]), 8, '0', STR_PAD_LEFT) , " ";
}
}
else
{
echo "Invalid IP!";
}
?>
它将输入的IP输出到二进制八位字节,就像这个11111111 0001000 10010101 10010101
一样,它们在八位字节之间有空格,我如何拆分它们并将其存储到全局可访问的数组中?
由于
答案 0 :(得分:1)
您可以使用$arr=explode(' ', "11111111 0001000 10010101 10010101");
答案 1 :(得分:1)
而不是回应你的结果将它们存储到类似这样的数组
<?php
$octets = array($_POST["oct1"],$_POST["oct2"],$_POST["oct3"],$_POST["oct4"]);
$octlenfnl = count($octets) - 1;
$binoctstr = 0 ;
$binaryarray = array();
if($_POST["oct1"] <= 255 && $_POST["oct1"] <= 255 && $_POST["oct1"] <= 255 && $_POST["oct1"] <= 255)
{
for($i=0;$i<=$octlenfnl;$i++){
$binaryarray[] = str_pad(decbin($octets[$i]), 8, '0', STR_PAD_LEFT);
}
}
else
{
echo "Invalid IP!";
}
//to echo out your results you can do this as a comma separated string
echo implode(",",$binaryarray);
//or if you wish to access a specific segment you can do this where $key is the array element you want
echo $binaryarray[$key];
?>
更新简化编码的编辑
你可以稍微简化一下我认为这样的代码,除非你创建第二个数组并只是操纵你现有的数组。除非你需要任何初始数组,否则这应该可以正常工作
<?php
$octets = array($_POST["oct1"],$_POST["oct2"],$_POST["oct3"],$_POST["oct4"]);
$binoctstr = 0 ;
if($_POST["oct1"] <= 255 && $_POST["oct1"] <= 255 && $_POST["oct1"] <= 255 && $_POST["oct1"] <= 255)
{
for($i=0;$i<=count($octets);$i++){
$octets [$i] = str_pad(decbin($octets[$i]), 8, '0', STR_PAD_LEFT);
}
}
else
{
echo "Invalid IP!";
}
//to echo out your results you can do this as a comma separated string
echo implode(",",$octets );
//or if you wish to access a specific segment you can do this where $key is the array element you want
echo $octets[$key];
?>
答案 2 :(得分:0)
使用此
$resultAsArray = explode(" ", $binaryOctets);