dsaeyrq451928 2019-04-10 10:16
浏览 18

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

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 ")
?>
  • 写回答

1条回答 默认 最新

  • dongnao3990 2019-04-10 10:52
    关注

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

报告相同问题?

悬赏问题

  • ¥15 win2012磁盘空间不足,c盘正常,d盘无法写入
  • ¥15 用土力学知识进行土坡稳定性分析与挡土墙设计
  • ¥70 PlayWright在Java上连接CDP关联本地Chrome启动失败,貌似是Windows端口转发问题
  • ¥15 帮我写一个c++工程
  • ¥30 Eclipse官网打不开,官网首页进不去,显示无法访问此页面,求解决方法
  • ¥15 关于smbclient 库的使用
  • ¥15 微信小程序协议怎么写
  • ¥15 c语言怎么用printf(“\b \b”)与getch()实现黑框里写入与删除?
  • ¥20 怎么用dlib库的算法识别小麦病虫害
  • ¥15 华为ensp模拟器中S5700交换机在配置过程中老是反复重启