简体   繁体   English

PHP strlen()和字符串宽度

[英]PHP strlen() and width of string

Not sure if there's a php function that can help determine this. 不知道是否有一个PHP函数可以帮助确定这一点。

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. 两者都有9个字符。 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. 对于某些字体(不确切知道哪种字体,但我想例如Courier),宽度直接与字符数成正比,因此可以对字符串进行简单填充。 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. 尝试使用CSS对齐它们。

As vucetica mentioned monospaced fonts like Courier or Courier New could help you to archive equal spacing between characters. 正如vucetica所提到的,诸如CourierCourier New类的等宽字体可以帮助您将字符之间的等距归档。

Also if you want to make sure that all strings are same length for example 32 characters you can use sprintf method 另外,如果要确保所有字符串的长度相同(例如32个字符),则可以使用sprintf方法

$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 可以在PERL 文档中找到更多语法示例,其中90%可在php中使用

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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