views:

120

answers:

3

i have stored two ip address values in two strings

a = '116.95.123.111'
b = '116.95.122.112'

i just want to compare the first two parts of ip address i.e 116.95 part in the two strings and as it is same in both the strings my comparison should return true. how to do this partial string comparison in PHP?

+6  A: 

substr_compare is binary safe.

Lex
+3  A: 

in this particular case (comparing ip addresses)

if((ip2long($a) >> 16) == (ip2long($b) >> 16)) echo "equal";
stereofrog
+3  A: 

IP adresses can contain leading zeroes. When exploding, they can be compared to as integers, so that leading zeroes are ignored.

$a = "116.95.123.111";
$b = "116.095.123.111"   // same IP as $a, but with leading zero

The "clean" way would be by something like this...

$ip1 = explode(".", $a);
$ip2 = explode(".", $b);

if (($ip1[0] == $ip2[0]) && (ip1[1] == $ip2[1])) {
  // success. Do something
} else {
  // not valid
}
Martin Hohenberg