Php 替换长度大于等于40的字符串中的单词
我有以下代码:Php 替换长度大于等于40的字符串中的单词,php,string,Php,String,我有以下代码: $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 = $picture->getCaption();
$words = explode(" ", $caption);
foreach ($words as $word) {
$string_length = strlen($word);
if ($string_length > 40) {
str_replace($word, '', $caption);
$picture->setCaption($caption);
}
}
但是,为什么不将标题替换为删除的已修剪单词?您需要指定替换内容:
$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);
$caption=$picture->getCaption();
//按空格分解,然后过滤掉
//获取刚好在40个字符限制内的所有元素
//他们在内爆的情况下把它们重新组合在一起
$caption=内爆(“”,数组过滤器(“”,$caption),函数($piece){
返回mb_strlen($piece)setCaption($caption);
您需要这样做:
$caption = $picture->getCaption();
$words = explode(" ", $caption);
foreach ($words as $word)
{
$string_length = strlen($word);
if ($string_length > 40) {
$picture->setCaption(str_replace($word, '', $caption));
}
}
你必须这样做:
$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);
}
}
您正在替换但未存储ITI如果处理非ansi字符,strlen可能不够。