I needed to anonymize IPv4 and IPv6 addresses so I coded this crude solution: 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? Answer No conditional is necessary. You can write two patterns