Remove whitespace (spaces) from a string with PHP and preg_replace

Seeing as ereg_replace and that whole family has been depreciated in the newer PHP releases it’s surprising how many sites still show and use it.

This simple function strips out whitespace from a string. Could be useful in taking spaces out of usernames, id’s, etc.

<?php
$string = 'us er na  me';
$string = nowhitespace($string);
function nowhitespace($data) {
return preg_replace('/\s/', '', $data);
}
// This will be 'username' now
echo $string;
?>

You could use this to make all whitespace only 1 space wide by changing the ” in the following line.

return preg_replace('/\s/', ' ', $data);

Last example modified from the PHP manual.

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

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.