views:

148

answers:

5

Hi

I have a string that must fit into a box, and must be at most 3 lines long. To shorten it, I plan to truncate it and end it with '...'. I could shorten it to a certain # of characters but if i make it look good with "wwwwwwwww [...] wwww" it won't look right with "iiiiiiiiiii [...] iiii".

Is there some way I can shorten it by how much space the string would take up, as opposed to how many characters there are in a string without using a fixed-width font? Ideally I'd like to do this server-side (php) but recognize that actual character width stuff is far more likely to be feasible client-side (JS / jQuery)

Mala

ps. Please no "simply create an image of '...' and overlay it over the end of the line" hacks or similar - I actually want to shorten the string to the appropriate length

+2  A: 

There's imageftbbox and imagettfbbox for that.

Artefacto
very interesting solution - this would even work server-side :) Is this function quick though? I'm looking at having to do this 200+ times per page
Mala
Perfect, thanks! This looks like exactly what I wanted!
Mala
No ideia. benchmark it.
Artefacto
A: 

There's no way that I can think of to easily get font sizes to the degree that you speak of, but there may be a hack that would "appear" the way you want. I assume since you mention three lines, we're talking about a <textarea> element:

<textarea rows="3" cols="50" style="overflow:hidden;"></textarea>

Although the text is there, it's not visible and the scroll bars would not display.

BradBrening
+2  A: 

have a look at this: http://www.switchonthecode.com/tutorials/javascript-tutorial-how-to-auto-ellipse-text

lazerscience
This seems like the ideal JS solution - I'm still hoping for a quick server-side way, but barring that I'll probably end up going with this. Thanks!
Mala
+1  A: 

This site offers as good a way as any, and is cross-browser. I like the simplicity:

Robusto
This seems pretty much identical to lazerscience's solution - excellent find though, thanks :)
Mala
@Mala: There weren't any solutions when I posted. :)
Robusto
A: 

There is a number of jQuery plugins for this: http://plugins.jquery.com/taxonomy/term/2229

JLarky