-4

In PHP, I am try to use "loop" to remove all excessive spaces. (NOT use string trimming functions and string replacement functions) For example, " I Love PHP" > "I Love PHP". There should be only one space between words.

Any idea? Thank you

$newstr = " "  
for ($i = 0; $i < strlen($s), $i++ )  
{  
    $newstr = $newstr.substr($s, $i, 1);  
    if (substr($s, $i, 1) == " ")  
        while(substr($s, $i + 1, 1) == " ")  
            $i++;  
}  

print ("  test    test test ")
?>
Barmar
  • 741,623
  • 53
  • 500
  • 612
  • 4
    [ask]. Don’t ask for “ideas”, describe what problem you have with what you tried instead. – 04FS Apr 10 '19 at 10:17
  • 3
    Why did you tag this `python` ? – khelwood Apr 10 '19 at 10:19
  • 1
    Possible duplicate of [Remove excess whitespace from within a string](https://stackoverflow.com/questions/1703320/remove-excess-whitespace-from-within-a-string) – gabrielchl Apr 10 '19 at 10:19
  • 1
    @GabrielLee All the answers there use built-in functions that he's not allowed to use. – Barmar Apr 10 '19 at 10:36
  • 1
    FYI, `substr($s, $i, 1)` can be simplified to `$s[$i]`. – Barmar Apr 10 '19 at 10:37
  • Why do you print `" test test test "` at the end instead of `$newstr`? Why do you initialize `$newstr` with a single space instead of an empty string? – Barmar Apr 10 '19 at 10:38

1 Answers1

0

You have a syntax error in your for statement, it should be ; before $i++.

You need to start by skipping over all spaces at the beginning of the input string.

Any spaces at the end of the string will be compressed to a single space, you need to check for that and remove it.

<?php 
$newstr = "";
$s = "       I   Love     PHP   ";
$len = strlen($s);
// skip over initial spaces
while ($i < $len && $s[$i] == " ") {
  $i++; 
}
for (; $i < $len; $i++ )  
{  
  $newstr .= $s[$i];  
  if ($s[$i] == " ") { 
    while($i < $len-1 && $s[$i+1] == " ") {
      $i++;
    }
  }
}
if ($newstr[strlen($newstr)-1] == " ") {
  // remove trailing space
  $newstr = substr($newstr, 0, strlen($newstr)-1);
}
var_dump($newstr);
Barmar
  • 741,623
  • 53
  • 500
  • 612