Captain Harlock
Captain Harlock

Reputation: 57

Get the two last parts of an IP address in PHP

I'd like to get the two lasts octets from an IP address with PHP. I tried this :

substr(strrchr($ip,'.'),2);

But it seems I misunderstood the code, since it's not working... (eg. if my IP is 192.168.0.79, this line returns only "9"...)

Upvotes: 2

Views: 724

Answers (3)

u_mulder
u_mulder

Reputation: 54831

If you want last part as string, use explode with 3rd parameter:

$parts = explode('.', '192.168.0.79', 3);
echo $parts[2];    // "0.79"

// or even:
echo explode('.', '192.168.0.79', 3)[2];    // "0.79"

Upvotes: 3

Badiparmagi
Badiparmagi

Reputation: 1285

you can explode the ip string and get the parts from it.

    $ip = "192.168.0.79";
    $split = explode(".", $ip);
    $part1 = $split[2]; // 0
    $part2 = $split[3];// 79

Upvotes: 5

Hamza Abdaoui
Hamza Abdaoui

Reputation: 2209

Using your solution, just change 2 with 1:

substr(strrchr($ip,'.'),1); // Output 79

Upvotes: 4

Related Questions