views:

38

answers:

1

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.

+3  A: 

How about:

if (strlen($input) > $maxLen) {
    $characters = floor($maxLen / 2);
    return substr($input, 0, $characters) . '...' . substr($input, -1 * $characters);
}
VoteyDisciple
That only adds a `...` to the front of the string, so the output is `...reallyreallyreallyreallyreally`.
VIVA LA NWO
Er, it should put the `...` in the middle of the string James, there are two substr calls there.
Amber
I know there are. But if I put that code in my `cutString` function it returns a string with the ellipses at the front of the string.
VIVA LA NWO
But it does not take into account the three characters added by the '...', so with a maxLen of 30, the result string will be 33 characters long. $characters should not be more than floor(($maxLen-3)/2);
Ivar Bonsaksen
@James P, to put that code into your cutString, you will have to rename either your maxLen or VoteyDisciple's maxLength
Ivar Bonsaksen
Quite right; I misread that variable name. I've edited to rename `$maxLen`
VoteyDisciple
Yeah, spotted that a few seconds ago. Thank you for the code, i'll accept your answer when it lets me :)
VIVA LA NWO