Wrote the code:

<?php function delete_words($text){ $str = explode(' ', $text); foreach($str as $value){ if (mb_strlen($value)>5){ unset($str[$value]); } } print_r($str); } $text = "один двадцать три сорок восемь пятдесят"; delete_words($text); ?> 

But he displays all the words anyway, without deleting those that are longer than 5 letters. What is wrong here?

  • In Foreach $key => $value and change key - Naumov
  • thanks ... for sure! - Beginner

3 answers 3

The cycle needs to be written like this

 foreach($str as $index => $value){ if (mb_strlen($value) > 5){ unset($str[$index]); } } 

(note the $index variable)

    alternative method is to use array_filter

     $text = 'один два пять семнадцать три сорок семь два девятьнадцать'; $result = array_filter(explode(' ', $text), function ($word) { return mb_strlen($word) < 5; }); var_dump($result); 

    this function was created specifically for the approach used in the task (only not for the task itself, because small changes in conditions can chop off this path): take an abstract array, run it through the function, and based on the result of this function ("yes" - true or "no" - false) keep or delete the item.

      As an option:

       <?php $text = "один двадцать три сорок восемь пятдесят"; echo preg_replace('/[^\s]{6,}/ui', '', $text); // один три сорок 

      For specific tasks, the regular expression is adjusted. The above is the simplest option for an example.