Web Hosting Talk







View Full Version : Width of text algoritm (php)


beowulfdk
03-01-2008, 01:30 PM
Hi,

Does anyone know of an algoritm that will give an indication of the width of a text string rendered with a typical true type font? What I mean is a way of getting an indicator (not actual pixel width) of how wide the string will be.

My problem is user names, on a site of mine, breaking the design when they've used certain wide characters or the full number of chars allowed in user names. Being able to get an indication of the width of a user name would enable me to force shortening certain user names when showing them.

isurus
03-01-2008, 05:48 PM
You may be better off tweaking your site so that it doesn't break, but....

If the user enlarges the text on the page via their web browser then your server-side calculation will be wrong anyway.

If you're just planning to truncate the username, why not set the overflow to hidden on the element that contains the username? This will avoid any additional processing overheads etc....

beowulfdk
03-02-2008, 08:19 AM
I found another simple trick. I use this code (I know that if the user has extremely large font then it will probably still break the design). But at least now the design will not break with normal fonts in IE or Firefox when someone uses a long username.

echo chunk_split($name,10,'<wbr>');

magixman
03-03-2008, 06:25 PM
Another way is to just truncate the text in the browser

<div style="width: 20px;overflow: hidden">Bla Bla Bla</div>

AmyWilliams
03-03-2008, 11:29 PM
I haven't tested this myself, but in JavaScript (and I suppose this can be adapted to fit with PHP), you could place the text in a div and get the div's width using getElementById['blah'].width