如何在PHP中获取ip地址字符串的最后一部分

时间:2014-11-14 08:15:51

标签: php

如果我有一个IP,如:

195.123.321.456

如何将456作为变量?

5 个答案:

答案 0 :(得分:7)

这应该适合你:

<?php

    $ip = "195.123.321.456";
    $split = explode(".", $ip);
    echo $split[3];

?>

输出:

456

答案 1 :(得分:1)

\b\d+(?![^.]*\.)

试试这个。看看演示。

http://regex101.com/r/pQ9bV3/22

$re = "/\\b\\d+(?![^.]*\\.)/";
$str = "195.123.321.456";

preg_match_all($re, $str, $matches);

答案 2 :(得分:1)

如果您将其存储在Var之类的

$var = "195.123.321.456";

你可以在字符串上使用前置的php命令来查找最后一次出现。

$number = substr(strrchr($var , "."), 1);

现在你将拥有456 $ $ var

strrchr上的文档 - &gt; http://php.net/manual/en/function.strrchr.php

答案 3 :(得分:1)

您可以通过以下方式找到:

$ipaddress = '195.123.321.456';

$endValue = end( explode(".", $ipaddress ) );

echo $endValue;

答案 4 :(得分:0)

你也可以使用这个:

$ip = '195.123.321.456';
$last = substr($ip, strrpos($ip, '.') + 1);