0

Not sure if there's a php function that can help determine this.

I have some strings with variable characters. My problem is how long the string is, not how many characters there are.

$str1 = '123456789';
$str2 = 'akIOuNBGH';

Both have 9 characters. However, the second is slightly longer in the browser, due to wider characters.

Ultimately I'd like to append '.............' a series of dots after the two strings, but since the second and first are not the same width, the uniformity is off.

Any cool ideas or ways on how to determine string width? Perhaps, if I know the width values, I can code the appended information appropriately.

coffeemonitor
  • 12,780
  • 34
  • 99
  • 149
  • 1
    I believe CSS would be better-suited for this. See http://www.css3.info/preview/text-overflow/. – 0b10011 Jan 12 '12 at 03:43
  • 1
    The string width depends on font, and I doubt there's a way to find out the default font. Try surrounding it with monospace, so all characters have the same width. – personak Jan 12 '12 at 03:45
  • You cannot determine the string width in your case, it has to be done on the client. Consider a javascript solution, which is simple as rendering the text in a div/span (either invisible or placed out of the screen) and retrieve its width. See: http://stackoverflow.com/questions/118241/calculate-text-width-with-javascript – al01 Jan 12 '12 at 03:57
  • What would the purpose be? Perhaps there is a better way to approach the situation you're given. If you're just asking for if there is PHP functionality out of the blue, there is the possibility of using [GD](http://php.net/gd) (maybe even [imagefontwidth](http://php.net/imagefontwidth)) in some crafty way). – Zack Zatkin-Gold Jan 12 '12 at 04:00

2 Answers2

1

Width depends on the type of font you use on the client side to represent those strings. For some fonts (don't know exactly which, but I think Courier for example), width is directly proportional to the number of characters, so simple padding of your strings will work. For other fonts, it will not work and will depend on how browsers render it. If you are trying to align your strings on the server side, you are doing it in the worst possible way. Try to align them using CSS.

Aleksandar Vucetic
  • 14,715
  • 9
  • 53
  • 56
0

As vucetica mentioned monospaced fonts like Courier or Courier New could help you to archive equal spacing between characters.

Also if you want to make sure that all strings are same length for example 32 characters you can use sprintf method

$string = '1234567890';
$string = sprintf("%'.-32s", $string);
var_dump($string); //string(32) "1234567890......................"

More syntax examples can be found in PERL documentation, 90% of which works in php

Community
  • 1
  • 1
Nazariy
  • 6,028
  • 5
  • 37
  • 61