The question implies that you need to delete the last 3 numbers after the last point. That is, the last 4 characters of IP
must be .***
.
So, I would do it this way:
preg_replace('/\d+$/', '***', '192.168.1.122')
The expression \d+
will only capture numeric values. The $
character is reporting that only expressions that end with \d
(digits).
Update
If you want to capture the last 4 numbers and turn it into *
, ignoring .
, I suggest using the following code:
preg_replace('/\d{1}\.\d+$/D', '*.***', '192.168.100.122')
preg_replace('/\d{1}\.\d+$/D', '*.***', '192.168.1.100')
Result:
192.168.10*.***
192.168.*.***
Using preg_replace_callback
.
I've also been able to work out a way to capture the last 4 digits, considering that the .
character must remain.
See:
$replacer = function ($m) {
return str_repeat('*', strlen($m[1])) . '.' . str_repeat('*', strlen($m[2]));
};
$result = preg_replace_callback('/(\d{1})\.(\d{1,3})$/', $replacer, '192.468.1.114');
See the example of preg_replace_callback
in IDEONE