Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

trim ip address octet

Tags:

php

I need to trim the last octet from an ip address using php. Basically I'm trying to just remove any digits after the third dot. I'm wondering if there is an out of the box solution for this? as my regex abilities are basic at best. Many thanks.

like image 505
Chris J Allen Avatar asked May 26 '09 09:05

Chris J Allen


2 Answers

$trimmed = implode(".", array_slice(explode(".", $ip), 0, 3));

or

$trimmed = substr($ip, 0, strrpos($ip, "."));

or possibly

$trimmed = preg_replace("/(\d{1,3})\.(\d{1,3}).(\d{1,3}).(\d{1,3})/", '$1.$2.$3', $ip);

A more mathematical approach that doesn't remove the last digit but rather replaces it with a 0:

$newIp = long2ip(ip2long("192.168.0.10") & 0xFFFFFF00);
like image 98
Emil H Avatar answered Sep 20 '22 18:09

Emil H


This will remove the last digits and the dot.

$trimmed = preg_replace('/\.\d{1,3}$/', '', $ip);
like image 33
Peter Stuifzand Avatar answered Sep 20 '22 18:09

Peter Stuifzand