Question

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.

Was it helpful?

Solution

How about:

if (strlen($input) > $maxLen) {
    $characters = floor($maxLen / 2);
    return substr($input, 0, $characters) . '...' . substr($input, -1 * $characters);
}
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top