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.
$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);
This will remove the last digits and the dot.
$trimmed = preg_replace('/\.\d{1,3}$/', '', $ip);
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With