Skip to content
Advertisement

Anonymize IPv4 and IPv6 addresses with PHP preg_replace?

I needed to anonymize IPv4 and IPv6 addresses so I coded this crude solution:

JavaScript

It works fine with full length IPv4 and IPv6 addresses like

207.142.131.005

2001:0db8:0000:08d3:0000:8a2e:0070:7344

but not with abbreviated addresses like

207.142.131.5

2001:0db8::8d3::8a2e:7:7344

I wonder if there is an elegant solution with preg_replace and some regular expression magic?

Advertisement

Answer

No conditional is necessary. You can write two patterns and two replacements for a single preg_replace() call to process.

Target the optional numbers after the last literal dot in the string for replacement. Then target the alphanumeric colon-delimited substrings at the end of the string.

Code: (Demo)

JavaScript

Output:

JavaScript

Pattern Explanations:

IPv4:

JavaScript

IPv6

JavaScript
User contributions licensed under: CC BY-SA
1 People found this is helpful
Advertisement