截断字符串,但删除字符串的中间而不是结尾 [英] truncate string, but remove middle of string instead of end

查看:26
本文介绍了截断字符串,但删除字符串的中间而不是结尾的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

I came up with this function that truncates a given string to either the given number of words or the given number of characters whatever is shorter. Then, after it chops off everything after the number of characters or words limit, it appends a '...' to the string.

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

How can I remove characters / words from the middle of the string and replace them with '...' instead of replacing characters / words at the end with the '...'?

这是我的代码:

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' 将被删除,而 '...' 将被附加.

For example if truncate('the quick brown fox jumps over the lazy dog', 8, 16); is called, 16 characters is shorter so that is the truncation that will happen. So, 'fox jumps over the lazy dog' will be removed and '...' will be appended.

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

But, instead, how can I have half of the character limit come from the beginning of string and half come from the end of string and what is removed in the middle replaced by '...'? So, the string I'm looking to be return in this, one, case would be: '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 现在是:

$result is now:

the quic...lazy dog

这篇关于截断字符串,但删除字符串的中间而不是结尾的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆