Wednesday, 28 January 2015

Remove redundant spaces - PHP

Remove redundant spaces - PHP
<?php
function remove_redundant_spaces($String = '')
{
  // :: Initalize Variables
  $Result = NULL;
  for ($i = 0; $i < strlen($String); $i++) {
    if (substr($String, $i, 1) != ' ') {
      $Result .= trim(substr($String, $i, 1));
    }
    else {
      while (substr($String, $i, 1) == ' ') {
        $i++;
      }
      $Result .= ' ';
      $i--;
    }
  }
  return $Result;
}

$String = 'This    string   contains    redundant    spaces';
$NewString = remove_redundant_spaces($String);
echo $NewString; // Output: This string conains redundant spaces

?>

0 comments:

Post a Comment