如何比较两个PhP变量中包含的两个IP地址的前三个八位字节[重复]

jq6vz3qz  于 2023-10-15  发布在  PHP
关注(0)|答案(5)|浏览(120)

此问题已在此处有答案

php select from mysql where title begins with A (and A alone)(5个答案)
mysql match string with start of string in table(2个答案)
昨天关门了。
我有两个php变量,其中包含两个ipv4地址,我需要比较前三个八位字节,如果匹配,则返回true,如果不匹配,则返回false。帮助写一个代码块是赞赏。

<?php
include('adodb/adodb.inc.php');
mysql_connect("173.86.45,9","abcd","1236");
mysql_select_db("vc");
$pl=mysql_query("SELECT stat_ip from Hasoffers");
$count=mysql_num_rows($pl);

while($row=mysql_fetch_array($pl))
{
$stat_ip=$row['stat_ip'];
echo sec($stat_ip)."<br>";
}

function sec($stat_ip)
{
  $result = mysql_query("select stat_ip from Hasoffers where stat_ip ='".$stat_ip."'");


                  if(condition to check if the octets match)
                {
                  //i need to write the condition if within the table Hasoffers, there are more than 2 'stat_ip'(column) values, having the same 3 octets.
                   printf("true");

                   }

               else
              {
                printf("false, octets don't match");

              }
                 return $num_rows;
}


?>
eivnm1vs

eivnm1vs1#

实现这一点的简单方法是:

$ip1 = '192.168.0.1';
$ip2 = '192.168.0.2';

$ip1 = explode('.', $ip1);
$ip2 = explode('.', $ip2);
if ($ip1[0]==$ip2[0] && $ip1[1]==$ip2[1] && $ip1[2]==$ip2[2]) {
    //your code here
}

编辑:尝试用这个函数替换你的sec()函数(阅读评论),然后编辑它。

function sec($stat_ip)
{
$octets = explode('.', $stat_ip);
$first_three = $octets[0].'.'.$octets[1].'.'.$octets[2].'.'; //this looks like 192.168.0.
  $result = mysql_query("SELECT stat_ip from Hasoffers where stat_ip LIKE '".$first_three."%'"); //this gives you all ip's starting with the current ip
  if (mysql_num_rows($result)>1) 
  {
    //we have more than one ip starting with current ip
    //do something here
  }
  else
  {
    //result returns 1 or 0 rows, no matching ip's
  }
   //return $something;
}
dvtswwa3

dvtswwa32#

使用strrpossubstr函数的解决方案:

$ip1 = '192.168.10.121';
$ip2 = '192.168.10.122';

// the position of the last octet separator
$last_dot_pos = strrpos($ip1, '.');
$is_matched = substr($ip1, 0, $last_dot_pos) == substr($ip2, 0, $last_dot_pos);

var_dump($is_matched);

输出:

bool(true)
irtuqstp

irtuqstp3#

使用此代码:

$ipOne = "192.168.1.1";
    $ipTwo = "192.168.1.2";

    $ipOneParts = explode(".", $ipOne);
    $ipTwoParts = explode(".", $ipTwo);

    if(($ipOneParts[0] == $ipTwoParts[0]) && 
       ($ipOneParts[1] == $ipTwoParts[1]) && 
       ($ipOneParts[2] == $ipTwoParts[2])){
        return true;
    } else {
        return false;
    }
umuewwlo

umuewwlo4#

将它们转换为数组使用explode使用“.”并比较两个数组的第一个索引。

pengsaosao

pengsaosao5#

function ip_clip($ip)
{
  $bits = explode('.', $ip);

  if(count($bits)) array_pop($bits);

  return implode('.', $bits);
}

if(ip_clip($ip1) == ip_clip($ip2))
{
  // your code here
}

相关问题