Squeezing strings in PHP

I've always thought the way Windows uses ellipses in the middle of a long string was quaint. It's great except for the fact that sometimes it trims out the important bits. Here's a little php function that I wrote to trim out the middle part of a string. I suppose you could use it to trim out important bits, too.

The maximum string length and the number of characters at the end have to be specified. This is ideal for strings of text that look identical at the beginning and are usually distinguished by the last part. An example would be file names with their paths included or full URLs.

function shorten($text, $count, $tail)
    {
        if (strlen($text)>$count)
        {
            // … is the unicode ellipses character
            return (substr_replace(
                         $text,
                         '…',
                         $count-$tail-1,
                         strlen($text)-$count+1 ));
        }
        else
        {
            return $text;
        }
    }

Of course, this deals with character counts, not the actual rendered length of the text, nobody knows that but the client. The real length will depend on the font chosen on the user end, but sometimes you can be pretty certain that your text will be too long to be displayed completely. If you wanted to trim based on the final rendered length, I think you'd have to do some funny Javascript or CSS tricks. I know SVG allows you to set the rendered length of text, but that's not an option today on the wild wild web. I see that CSS 2.1 lets you specify the spacing but not the total length. A CSS 3 Text Effects Module was just announced today, but I don't see anything in there equivalent to the textLength and lengthAdjust in SVG. Although a few of the properties sound like it, it doesn't look like any of them do any more than let you adjust character, word, or punctuation spacing.

For now, I'll just stick to my php function when it suits and lament the state of markup languages when it doesn't.

0
Your rating: None

That is useful, I've been looking for something like that. Thanks. More posts in the PHP section, please!