Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

truncate string, but remove middle of string instead of end

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 '...'?

Here is my code:

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 ? '' : '...');
}

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.

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'.

like image 267
irfan mir Avatar asked Jun 01 '13 05:06

irfan mir


1 Answers

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

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

$result is now:

the quic...lazy dog
like image 73
Ziarno Avatar answered Sep 21 '22 12:09

Ziarno