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 to share