Reputation: 9583
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?
Upvotes: 0
Views: 903
Reputation: 3323
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
}
Upvotes: 4
Reputation: 53950
in this particular case (comparing ip addresses)
if((ip2long($a) >> 16) == (ip2long($b) >> 16)) echo "equal";
Upvotes: 4