Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
264 views
in Technique[技术] by (71.8m points)

php - Aligning based on the width of letters with sprintf

I'm attempting to align a text-based list of items for an e-mail. Basically the problem I have is that it only works with fixed-width (monospaced) fonts - I'd like a script that somehow can align it based on the width of each letter in a standard Arialish font.

function sprintf_nbsp() {
   $args = func_get_args();
   return str_replace(' ', ' ', vsprintf(array_shift($args), array_values($args)));
}
$format = '%-6s%-'.35.35s...%'.10s<br>';
$str = sprintf_nbsp($format, '1', 'A list of items - this is the first', '$49.99');
$str .= sprintf_nbsp($format, '100', 'This is something else', '$4.99');
$str .= sprintf_nbsp($format, '5', 'A book', '$499.99');
$str .= sprintf_nbsp($format, '16', 'Testing the function', '$49.99');
echo '<div style="font-family:Courier">'.$str."</div>";
echo '<br><br>'.$str;

(the sprintf_nbsp() may not be necessary, I just found it on the php forums, I'm open to other solutions)

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

fixed-width (monospaced) fonts - I'd like a script that somehow can align it based on the width of each letter in a standard Arialish font.

Simply put, this is impossible.

With a fixed-width font every character has the same width, hence the name, fixed width.

With other fonts this is not the case. For example, you can plainly see that the i is much narrower than the M.

You can't know which font the user uses, even if you specify something like font-family: Arial this may not always work, different systems (OSX, X11, etc.) use different fonts, and some users also override font website's settings, etc.

And even if you knew for 100% certainty which font the user uses, it would be pretty much impossible to align everything to be pixel-perfect.

So, you have two options: either use a fixed width font ("Consolas" is a standard Windows font which looks fairly good), or use a different layout.

What you probably want is something like this:

<style>
  span { display: block; width: 20em;}
</style>

<span>Some text</span>
<span>Hello, world!</span>
<span>A swallow could not carry a coconut</span>

Here, every <span> is the same width (20em) regardless of the amount of text it contains.

Using spaces to align stuff is almost always a bad idea. Using CSS is not only much cleaner, it's also a lot easier.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

1.4m articles

1.4m replys

5 comments

57.0k users

...