Skip to content

Instantly share code, notes, and snippets.

@Dan0sz
Last active January 23, 2022 21:35
Show Gist options
  • Select an option

  • Save Dan0sz/62709d911ea6112b3ca8b45b52cd4a6a to your computer and use it in GitHub Desktop.

Select an option

Save Dan0sz/62709d911ea6112b3ca8b45b52cd4a6a to your computer and use it in GitHub Desktop.
Anonymize the last two octets of an IP address, by replacing it with 0 (zero)
<?php
$octets = explode('.', $ip);
/**
* Instead of using Regex and str_replace, we're slicing the array parts
* and rebuilding the ip (implode) to make sure no duplicate values are
* replaced.
*
* E.g. using str_replace or preg_replace; 192.168.1.1 would result in 092.068.0.0.
*/
$second_to_last = array_slice($octets, -2, 1, true);
$second_to_last_key = array_key_first($second_to_last);
$second_to_last[$second_to_last_key] = '0';
$last = array_slice($octets, -1, 1, true);
$last_key = array_key_first($last);
$last[$last_key] = '0';
/**
* Replace each octet with the with the
*/
$octets = array_replace($octets, $second_to_last, $last);
return implode('.', $octets);
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment