If you use the default padding specifier (a space) and then print it to HTML, you will notice that HTML does not display the multiple spaces correctly. This is because any sequence of white-space is treated as a single space.
To overcome this, I wrote a simple function that replaces all the spaces in the string returned by sprintf() with the character entity reference " " to achieve non-breaking space in strings returned by sprintf()
<?php
function sprintf_nbsp() {
$args = func_get_args();
return str_replace(' ', ' ', vsprintf(array_shift($args), array_values($args)));
}
$format = 'The %d monkeys are attacking the [%10s]!';
$str = sprintf_nbsp($format, 15, 'zoo');
echo $str;
?>
The above example will output:
The 15 monkeys are attacking the [ zoo]!
<?php
function printf_nbsp() {
$args = func_get_args();
echo str_replace(' ', ' ', vsprintf(array_shift($args), array_values($args)));
}
?>