15

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

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

这是我的代码:

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 个字符会更短,因此会发生截断。因此,“狐狸跳过懒狗”将被删除,而“...”将被附加。

但是,相反,我怎样才能让字符限制的一半来自字符串的开头,一半来自字符串的结尾,而中间删除的内容被“...”替换?所以,我希望在这个案例中返回的字符串是:'the quic...lazy dog'。

4

3 回答 3

34
$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
于 2013-06-01T05:12:12.187 回答
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;
}
于 2016-08-05T12:36:16.660 回答
3

这是我最终使用的:

/**
 * Removes characters from the middle of the string to ensure it is no more
 * than $maxLength characters long.
 *
 * Removed characters are replaced with "..."
 *
 * This method will give priority to the right-hand side of the string when
 * data is truncated.
 *
 * @param $string
 * @param $maxLength
 * @return string
 */
function truncateMiddle($string, $maxLength)
{
    // Early exit if no truncation necessary
    if (strlen($string) <= $maxLength) return $string;

    $numRightChars = ceil($maxLength / 2);
    $numLeftChars = floor($maxLength / 2) - 3; // to accommodate the "..."

    return sprintf("%s...%s", substr($string, 0, $numLeftChars), substr($string, 0 - $numRightChars));
}

对于我的用例,字符串的右侧包含更多有用的信息,因此此方法偏向于将字符从左半部分中取出。

于 2016-05-22T18:11:47.483 回答