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.
+5
A:
$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);
Emil H
2009-05-26 09:33:33
what more could i ask for? have a great day! :)
Pickledegg
2009-05-26 09:39:51
OMG, what a nice way to demonstrate the "there is more way to do it right" rule, respect!
Csaba Kétszeri
2009-05-26 15:42:56
A:
Regexp vatiant
$ip = '192.168.20.10';
preg_replace_callback(
'/^(\d{1,3})\.(\d{1,3})\.(\d{1,3})\.(\d{1,3})$/'
, create_function('$matches', '$matches[4] = "0"; array_shift($matches); return implode(".", $matches);')
, $ip
);
You could also use ip2long and long2ip... but have no idea about "box solution" with it:
$ip = ip2long('192.168.20.10') - 10;
echo long2ip($ip);
Jet
2009-05-26 09:50:43
+2
A:
This will remove the last digits and the dot.
$trimmed = preg_replace('/\.\d{1,3}$/', '', $ip);
Peter Stuifzand
2009-05-26 10:07:04