Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Cutting down a length of a PHP string and inserting an ellipses

I want to turn a long string like reallyreallyreallyreallyreallylongfilename into something like reallyreallyre...yreallyreally.

Basically, find the middle of the string and replace everything there until the length of the string is < 30 characters including an ellipses to signify there has been parts of the string replaced.

This is my code where I have tried this:

function cutString($input, $maxLen = 30)
{
    if(strlen($input) < $maxLen)
    {
        return $input;
    }

    $midPoint = floor(strlen($input) / 2);
    $startPoint = $midPoint - 1;

    return substr_replace($input, '...', $startPoint, 3);
}

It finds the center of the string and replaces a character either side with . but the thing is I can't work out how to make it cut it down to 30 characters, or whatever $maxLen is.

Hopefully you understand my question, I don't think I did a very good job at explaining it 8)

Thanks.

like image 659
VIVA LA NWO Avatar asked Jun 19 '10 17:06

VIVA LA NWO


1 Answers

How about:

if (strlen($input) > $maxLen) {
    $characters = floor($maxLen / 2);
    return substr($input, 0, $characters) . '...' . substr($input, -1 * $characters);
}
like image 187
VoteyDisciple Avatar answered Oct 23 '22 08:10

VoteyDisciple