Using PHP to strip a user IP address into subnets and filter out characters

April 03, 2010

Found it very difficult to find a simple solution to this problem - you want to display the submittor's IP address on a webpage where it will be publicly available, but obfuscate some characters.

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;

Of course, if you're happy to just cut off the end then you can use the substr function to trim a number of characters off.

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


Profile picture

From Dave, who writes to learn things. Thoughts and views are his own.

© 2024, withdave.