partial string comparision in php
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 string开发者_开发百科s and as it is same in both the strings my comparison should return true. how to do this partial string comparison in PHP?
substr_compare
is binary safe.
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
}
in this particular case (comparing ip addresses)
if((ip2long($a) >> 16) == (ip2long($b) >> 16)) echo "equal";
精彩评论