Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Get the two last parts of an IP address in PHP

Tags:

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"...)

like image 758
Captain Harlock Avatar asked Dec 11 '25 08:12

Captain Harlock


2 Answers

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
like image 118
Badiparmagi Avatar answered Dec 13 '25 21:12

Badiparmagi


Using your solution, just change 2 with 1:

substr(strrchr($ip,'.'),1); // Output 79
like image 29
Hamza Abdaoui Avatar answered Dec 13 '25 23:12

Hamza Abdaoui



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!