Last active
January 23, 2022 21:35
-
-
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)
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| <?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