irfan mir irfan mir - 1 year ago 36
PHP Question

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){
$truncated[]=substr($fragment, 0, $maxChars - $chars);

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

$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