PHP sprintf空间填充

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]
",    $phpPartHrsMls); // right-justification with spaces

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!

you use %06d please try some larger number .

your code can some thing like below try :

printf('%20.2f', $phpPartHrsMls);

and you can use &nbsp; for space on your html .

Changing leading zeroes to leading spaces:

$formatted_value = sprintf("%' 6s", $phpPartHrsMls);

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.