Forum Moderators: coopster

Message Too Old, No Replies

any way to determine physical length of a string

I'm trying to truncate a string by width in pixels, not characters

         

gilahacker

12:10 am on Jan 20, 2005 (gmt 0)

10+ Year Member



I have a box on my website that lists out the titles and short descriptions of some news articles. These can vary greatly in length.

My problem is that while I can trim these to be no more than "x" number of characters, some charecters are wider in pixels than others (i.e. "X" and "i"), depending on the font of course, which results in some strings being broken up into 3 lines, and some into 4 lines, forcing content out of the box at the bottom.

I'd like to be able to truncate my strings at exactly 3 lines of text, and as I said, truncating by number of characters is not an exact science.

The only way I can think to do this would be to figure the width of the text in pixels, and short of having a table with the widths of all the characters to reference and calculating total width by that I'm at a loss for a solution.

Any ideas?

Thanks,
-Jason

Thinking further into this, word wrap is probably going to wreak havoc on any attempts to do what I'm trying to do as it will force longer words down to the next line. Perhaps there is no real solution to this one.

[edited by: jatar_k at 4:38 am (utc) on Jan. 20, 2005]
[edit reason] no sigs thanks [/edit]

jatar_k

4:41 am on Jan 20, 2005 (gmt 0)

WebmasterWorld Administrator 10+ Year Member



the only thing I can think of is using a fixed width font or truncating your strings to something that will be safe even if it is using the widest character.

The thing is you have no control over the user's settings anyway. People who are visually impaired or have poor sight may use very large font settings and then you are in trouble anyway. So your site needs to be able to scale regardless.

dcrombie

10:39 am on Jan 20, 2005 (gmt 0)



This is possible in Java using "FontMetrics". Probably something equivalent exists in GD as well.

You might need to create a graphic though, unless the 'FontMetric' results can be fed back to PHP from Java/GD...

;)