图像处理-是否有一种方法可以将字符串长度转换为PHP中strlen()派生的字符串长度


image manipulation - Is there a way to convert string length as derived from something like strlen() into pixel length in PHP?

例如:

<?php
$string = 'Foo bar';
$length = strlen($string);
echo '<div style="width: '.$length.'px;">'.$string.'</div>';

上面显然不起作用,因为$length为7,而7px小于输出文本的大小。

我也明白字体大小和其他因素也会起作用。

我要找的是这样的东西:

<div style="width:xxx; float:left;">Label 1</div><input type="checkbox"/><br/>
<div style="width:xxx; float:left; clear:left;">Longer Label 2</div> <input type="checkbox"/><br/>
<div style="width:xxx; float:left; clear:left;">Even Longer Label 3</div> <input type="checkbox"/><br/>

如果你知道你将使用的字体,你想知道imagettfbbox()

但是,是的,只是不给宽度和右对齐文本,或使用网格系统布局,如Bootstrap或960.gs。

我的理解是,您正在尝试将字符串的长度与相应的尺寸相匹配。正如您已经指出的,这只有在您考虑字体类型和大小时才有可能。假设你想要一个等间距的字体,你必须将$length与一个因子相乘。

同样,如果你将display属性的值设置为inline-block,div元素的行为就像一个块元素,但它的宽度随着它包含的元素而变化display: inline-block