如何使用PHP和正则表达式屏蔽/隐藏IP地址(字符串)

I would like to hide the last two sections from an IP address using regular expression the problem is that the asterix (*) must match the length of those sections.

Eg: 10.101.12.100 should be re-formated into 10.101.**.***

This is the code I'm working with :

echo preg_replace('!(\d+).(\d+).\d+.\d+!s', '${1}.${2}.***.***', "10.101.12.100");
// Return: 10.101.***.***

Is that possible using regex ?

PS: I know I could break it using explode('.', ...) along with str_repeat('*', strlen(...)) but I find preg_replace a cleaner solution. I'm looking for a "oneliner" solution.

Use a negative look-ahead (Basically, have regex disqualify the first two octets, then do a normal digit replace from thereafter.) e.g.

(?!\d{1,3}\.\d{1,3}\.)\d

Demo

Example output:

237.134.85.92 -> 237.134.**.**
173.14.176.182 -> 173.14.***.***
167.209.41.203 -> 167.209.**.***
137.133.204.130 -> 137.133.***.***
93.108.72.157 -> 93.108.**.***

That might be a bit of an abuse of a regex. The following is probably faster, safer, and easier to understand...

  1. Explode string on "."
  2. Replace all chars in array index 2, 3 with "*"
  3. Join with "."
  4. profit.