我有以下代码:
$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);
}
}
但是,为什么不删除修剪后的字词来替换字幕?
答案 0 :(得分:2)
您需要指定替换品:
$caption = str_replace($word, '', $caption);
我认为这要好得多:
$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);
答案 1 :(得分:2)
你需要这样做:
$caption = $picture->getCaption();
$words = explode(" ", $caption);
foreach ($words as $word)
{
$string_length = strlen($word);
if ($string_length > 40) {
$picture->setCaption(str_replace($word, '', $caption));
}
}
答案 2 :(得分:1)
你必须这样做:
$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);
}
}