Replacing a word in a string of 40 or more length

I have the following code:

$caption = $picture->getCaption();
$words = explode(" ", $caption);
foreach ($words as $word) {
    $string_length = strlen($word);
    if ($string_length > 40) {
        str_replace($word, '', $caption);
        $picture->setCaption($caption);
    }
}

      

However, why doesn't this replace the deleted word signature?

+3


source to share


3 answers


You need to schedule a replacement:

$caption = str_replace($word, '', $caption);

      



I think this is much better:

$caption = $picture->getCaption();
// explode them by spaces, filter it out
// get all elements thats just inside 40 char limit
// them put them back together again with implode
$caption = implode(' ', array_filter(explode(' ', $caption), function($piece){
    return mb_strlen($piece) <= 40;
}));
$picture->setCaption($caption);

      

+3


source


You need to do the following:



$caption = $picture->getCaption();
$words = explode(" ", $caption);
foreach ($words as $word)
{
  $string_length = strlen($word);
  if ($string_length > 40) {
       $picture->setCaption(str_replace($word, '', $caption));
   }
}

      

+3


source


You should do it like this:

$caption = $picture->getCaption();
$words = explode(" ", $caption);
foreach ($words as $word)
{
  $string_length = strlen($word);
  if ($string_length > 40) {
      $replaced = str_replace($word, '', $caption);
      $picture->setCaption($replaced);
  }
}

      

+2


source







All Articles