Tag Archives: recursive

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…)

PHP: Implode a Multi-dimensional Array CodeUnit 09 APR 2010

PHP’s implode is a pretty handy function to flatten any array into a single string value, using any piece of ‘glue’ (basically a substring) that you specifiy to put everything together.

So in other words, if we had an array containing the string values of cat, dog and chicken and then ran the implode function against them using the character ‘|’ as glue, we would end up with a single string value reading cat | dog | chicken.

Of course, extending this function to handle multi-dimensional arrays (or matrices if you prefer) is a pretty simple matter of quickly whipping up a recursive version and so without any further waffling from my side, here’s the code:

//flattens a multi-dimensional array (recursive implode)
//-----------------------------------------------------------
function r_implode( $glue, $pieces )
{
	foreach( $pieces as $r_pieces )
	{
    		if( is_array( $r_pieces ) )
    		{
      			$retVal[] = r_implode( $glue, $r_pieces );
    		}
    		else	
    		{
      			$retVal[] = $r_pieces;
    		}
  	}
  	return implode( $glue, $retVal );
} 
//-----------------------------------------------------------

Usage is pretty simple. Call the r_implode function as normal, passing to it the ‘glue’ string you wish to employ as well as the array against which to run it.

Have fun.