简体   繁体   中英

PHP strlen() and width of string

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.

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.

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM