ABurntC00KIE
ABurntC00KIE

Reputation: 13

Shorten string NOT based on character count

I'm using steam's openID as part of my php website, meaning some usernames can be quite long.

When I display them, I want to shorten them so they fit within a certain space.

My current solution is:

$string = (strlen($alias) > 20) ? trim(substr($alias,0,20), ' ') . '...' : $alias;

So I basically take the first 20 chars of a username and add '...' on the end.

This works okay, however gamers make weird usernames and the difference in actual displayed pixels between "iiiiiiiiiiiiiiiiiiii" and "wwwwwwwwwwwwwwwwwwww" is quite large in most fonts. (W's would require me to limit it to 13 characters, while i's allow up to 41, 20 kinda works but some names are cut a lot shorter than others)

I could opt for a font with equal spacing, but they aren't usually as nice looking.

What are my options?

Upvotes: 1

Views: 45

Answers (2)

Satish Sharma
Satish Sharma

Reputation: 9635

You can achieve this by using css try this

HTML :

<div id="div_wrap">
wwwwwwwwwwwwwwwwwwww
</div>

<div id="div_wrap">
iiiiiiiiiiiiiiiiiiii
</div>

CSS :

#div_wrap{
  width: 50px;
  white-space: nowrap;
  overflow: hidden;
  text-overflow: ellipsis;
}

SEE DEMO

Upvotes: 0

Andrew
Andrew

Reputation: 5340

I think it's better to use css text-overflow: ellipsis instead:

  overflow: hidden;
  text-overflow: ellipsis;

http://jsfiddle.net/j582h/

http://www.w3schools.com/cssref/css3_pr_text-overflow.asp

Upvotes: 3

Related Questions