PHP Function to Remove all Double and Triple Spaces from a String Programming 19 MAR 2013

kung-fu-php-logoAn often overlooked tweak when cleaning a user or system input string is to make sure that there aren’t any double, triple or basically multiple instances of a space character next to one another, possibly caused by string concatenation or just a sticky spacebar key.

Below is a handy little function which works in a recursive manner to ensure that our input string only contains single instances of the space character:

function compressMultiSpacesToSingleSpace($inputstring) {
    if (!(strpos($inputstring, '  ') === false)) {
        $inputstring = str_replace('  ', ' ', $inputstring);
        $inputstring = compressMultiSpacesToSingleSpace($inputstring);
    }
    return $inputstring;
}

Simple in design, but it gets the job done.

(Of course, it might have been even easier to achieve this through some nifty regex one could argue…)

About Craig Lotter

Software developer, husband and dad to two little girls. Writer behind An Exploring South African. I don't have time for myself any more.