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.

4
  • 1
    I believe CSS would be better-suited for this. See css3.info/preview/text-overflow. Commented Jan 12, 2012 at 3: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. Commented Jan 12, 2012 at 3: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: stackoverflow.com/questions/118241/… Commented Jan 12, 2012 at 3: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 (maybe even imagefontwidth) in some crafty way). Commented Jan 12, 2012 at 4:00

2 Answers 2

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.

Sign up to request clarification or add additional context in comments.

Comments

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

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.