gpt4 book ai didi

php - 截断字符串,但删除字符串的中间而不是结尾

转载 作者:可可西里 更新时间:2023-10-31 22:19:16 24 4
gpt4 key购买 nike

我想出了这个函数,它将给定的字符串截断为给定的单词数或给定的字符数,无论哪个更短。然后,在超出字符数或字数限制后,它会在字符串中附加一个“...”。

如何从字符串中间删除字符/单词并将其替换为“...”,而不是将末尾的字符/单词替换为“...”?

这是我的代码:

function truncate($input, $maxWords, $maxChars){
$words = preg_split('/\s+/', $input);
$words = array_slice($words, 0, $maxWords);
$words = array_reverse($words);

$chars = 0;
$truncated = array();

while(count($words) > 0)
{
$fragment = trim(array_pop($words));
$chars += strlen($fragment);

if($chars > $maxChars){
if(!$truncated){
$truncated[]=substr($fragment, 0, $maxChars - $chars);
}
break;
}

$truncated[] = $fragment;
}

$result = implode($truncated, ' ');

return $result . ($input == $result ? '' : '...');
}

例如,如果调用 truncate('the quick brown fox jumps over the lazy dog', 8, 16);,则 16 个字符较短,因此这就是将发生的截断。因此,“fox jumps over the lazy dog”将被删除,并附加“...”。

但是,相反,我如何才能让一半的字符限制来自字符串的开头,一半来自字符串的结尾,并且中间删除的内容被替换为“...”?因此,我希望在这种情况下返回的字符串是:'the quic...lazy dog'。

最佳答案

$text = 'the quick brown fox jumps over the lazy dog';
$textLength = strlen($text);
$maxChars = 16;

$result = substr_replace($text, '...', $maxChars/2, $textLength-$maxChars);

$result 现在是:

the quic...lazy dog

关于php - 截断字符串,但删除字符串的中间而不是结尾,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/16869287/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com