Remove multiple spaces from given string

Write a program to remove the multiple spaces from the given string

String str = “You     are     a                good   boy.”

Output: “You are a good boy”

  1. <?php
  2.  
  3. //without pattern mach
  4. $str = "I am a good boy";
  5. $str_length = strlen($str);
  6. $str_arr = str_split($str);
  7. for ($i = 0; $i < $str_length; $i++) {
  8. if (isset($str_arr[$i + 1])
  9. && $str_arr[$i] == ' '
  10. && $str_arr[$i] == $str_arr[$i + 1]) {
  11. unset($str_arr[$i]);
  12. } else {
  13. continue;
  14. }
  15. }
  16.  
  17. echo implode("", $str_arr);
  18. ?>

Leave a Reply