如何只使用“循环”来删除句子中的所有过多空格,而不使用字符串修剪功能和更换功能?

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 ")
?>

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