简体   繁体   English

如何从IP地址获取最后一位?

[英]how to get the last digit from the IP address?

Does anyone know how can I get the last digit number from the Ip address in php? 有谁知道如何从php的IP地址中获取最后一位数字?

example: 例:

$ip = '200.0.0.12';

How can I get only 12 from the IP address instead of 200.0.0.12? 如何从IP地址中仅获取12个而不是200.0.0.12?

假设ip格式正确(没有端口,ipv4等)

$last_digit = array_pop(explode('.', $ip))

I like Mike B's answer, but here's a possible alternative: use strrchr and substr : 我喜欢Mike B的答案,但这是一个可能的选择:使用strrchrsubstr

$ip = '200.0.0.12';
echo substr(strrchr($ip,'.'),1);

One advantage: it's supposed to be (a little) faster then Mike B's answer. 一个优点:它应该比Mike B的回答要快一点。

In my (very unscientific) timings i got an average runtime of 1.3562 seconds (500.000 iterations) versus 1.6590 seconds for the array_pop / explode version. 在我的时间(非常不科学)中,我的平均运行时间为1.3562秒(500.000次迭代),而array_pop / explode版本的平均运行时间为1.6590秒。

My alternative. 我的选择。 By this way you get last digit in number type, not in string 这样,您将获得数字类型的最后一位数字,而不是字符串

$ip = '200.0.0.12';
echo ip2long($ip) % 256;

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM