Search code examples
phpemailprintftext-formatting

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)


Solution

  • 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.