PHP中的部分字符串比较

发布于 2024-08-09 09:00:53 字数 206 浏览 1 评论 0原文

我已经在两个字符串中存储了两个 IP 地址值,

a = '116.95.123.111'
b = '116.95.122.112'

我只想比较两个字符串中 IP 地址的前两个部分,即 116.95 部分,因为这两个字符串中的值相同,所以我的比较应该返回 true 。如何在 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 strings and as it is same in both the strings my comparison should return true. how to do this partial string comparison in PHP?

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(3

燕归巢 2024-08-16 09:00:53

substr_compare 是二进制安全的。

substr_compare is binary safe.

凉薄对峙 2024-08-16 09:00:53

IP 地址可以包含前导零。爆炸时,可以将它们作为整数进行比较,以便忽略前导零。

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

“干净”的方式是这样的......

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

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

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
}
你怎么这么可爱啊 2024-08-16 09:00:53

在这种特殊情况下(比较 IP 地址)

if((ip2long($a) >> 16) == (ip2long($b) >> 16)) echo "equal";

in this particular case (comparing ip addresses)

if((ip2long($a) >> 16) == (ip2long($b) >> 16)) echo "equal";
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文