简体   繁体   中英

How do I get the last part of an ip address string in PHP

If I have an IP such as:

195.123.321.456

How do I get just the 456 as a variable?

This should work for you:

<?php

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

?>

Output:

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

Try this.See demo.

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

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

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

If you store it inside a Var like

$var = "195.123.321.456";

you can use the preposed php command on string to find the last occurence.

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

You will have now 456 on $number var

Documentation on strrchr -> http://php.net/manual/en/function.strrchr.php

You can find this the following way:

$ipaddress = '195.123.321.456';

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

echo $endValue;

U could use also this:

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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