Using PHP to strip a user's IP address into subnets & filter out characters

Found it very difficult to find a good solution to this problem on the net – you want to display the submittor’s IP address on a webpage where it will be publicly available, but obviously don’t want to put the whole thing up…what do you do?

You want 255.255.255.255 to become 255.255.255.x or something, right?

Preg_replace() an IP

So, assuming we have the user’s IP address, for this we could use the following server variable:

// Displays user IP address
$ip =  $_SERVER['REMOTE_ADDR'];

We can manipulate this with preg_replace.

// Displays user IP address with last subnet replaced by 'x'
$ip = preg_replace('~(\d+)\.(\d+)\.(\d+)\.(\d+)~', "$1.$2.$3.x", $ip);

So the code to get and change this IP would be:

// Sets user IP address
$ip =  $_SERVER['REMOTE_ADDR'];
// Sets user IP address with last subnet replaced by 'x'
$ip = preg_replace('~(\d+)\.(\d+)\.(\d+)\.(\d+)~', "$1.$2.$3.x", $ip);
// Displays user IP address as altered.
echo $ip;

I’ll revise this to validate and deal with proxies another time.