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

irf*_*mir 10 php string truncate

我想出了这个函数,它将给定的字符串截断为给定数量的单词或给定数量的字符,无论是更短的.然后,在字符数或字数限制之后切断所有内容后,它会在字符串后附加一个"...".

如何从字符串中间删除字符/单词并用'...'替换它们而不是用'...'替换末尾的字符/单词?

这是我的代码:

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 ? '' : '...');
}
Run Code Online (Sandbox Code Playgroud)

例如,如果truncate('the quick brown fox jumps over the lazy dog', 8, 16);被调用,则16个字符更短,因此将发生截断.因此,'狐狸跳过懒狗'将被删除,'...'将被追加.

但是,相反,我怎么能有一半的字符限制来自字符串的开头,一半来自字符串的结尾,中间删除的内容被'...'取代?因此,我希望返回的字符串,其中一个案例是:'quic ... lazy dog'.

Zia*_*rno 27

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

$result = substr_replace($text, '...', $maxChars/2, $textLength-$maxChars);
Run Code Online (Sandbox Code Playgroud)

$ result现在是:

the quic...lazy dog
Run Code Online (Sandbox Code Playgroud)

  • 需要一个`if($ textLength> $ maxChars)` (3认同)

cri*_*hoj 7

这不会改变短于 的输入$maxChars,并考虑替换的长度...

function str_truncate_middle($text, $maxChars = 25, $filler = '...')
{
    $length = strlen($text);
    $fillerLength = strlen($filler);

    return ($length > $maxChars)
        ? substr_replace($text, $filler, ($maxChars - $fillerLength) / 2, $length - $maxChars + $fillerLength)
        : $text;
}
Run Code Online (Sandbox Code Playgroud)