PHP sprintf space padding

13,539

Solution 1

In the browser, spaces will always be collapsed.

Try:

<pre><?php echo $formatted_value; ?></pre>

And once you're satisfied with that, take a look at the CSS white-space:pre-wrap - a very useful property!

Solution 2

This will align the left with spaces:

$formatted_value = sprintf("%6s", $phpPartHrsMls);
echo "<pre>" . $formatted_value . "</pre>";

This will align the right with spaces:

$formatted_value = sprintf("%-6s", $phpPartHrsMls);
echo "<pre>" . $formatted_value . "</pre>";

If you want to print only six digits, and others to remove:

$formatted_value = sprintf("%-6.6s", $phpPartHrsMls);
echo "<pre>" . $formatted_value . "</pre>";

One more thing, the browser will generally ignore the spaces, so it's better to wrap your output in <pre> tag.

Solution 3

Changing leading zeroes to leading spaces:

$formatted_value = sprintf("%' 6s", $phpPartHrsMls);
Share:
13,539
user2883088
Author by

user2883088

Updated on June 20, 2022

Comments

  • user2883088
    user2883088 almost 2 years

    I have the following line in my code which displays my output in 6 characters with leading zeros.

    $formatted_value = sprintf("%06d", $phpPartHrsMls);
    

    I want to replace the leading zeros with spaces. Have tried all the examples found by searching this site and others and cannot figure it out.

    Here are some I have tried:

    $formatted_value = sprintf("%6s", $phpPartHrsMls);
    
    $formatted_value = printf("[%6s]\n",    $phpPartHrsMls); // right-justification with spaces
    
  • zzapper
    zzapper over 2 years
    This works for the command line which is what I was looking for