|
|
 |
sprintf (PHP 3, PHP 4, PHP 5) sprintf -- Return a formatted string Descriptionstring sprintf ( string format [, mixed args [, mixed ...]] )
Returns a string produced according to the formatting string
format.
The format string is composed of zero or more directives:
ordinary characters (excluding %) that are
copied directly to the result, and conversion
specifications, each of which results in fetching its
own parameter. This applies to both sprintf()
and printf().
Each conversion specification consists of a percent sign
(%), followed by one or more of these
elements, in order:
An optional sign specifier that forces a sign
(- or +) to be used on a number. By default, only the - sign is used
on a number if it's negative. This specifier forces positive numbers
to have the + sign attached as well, and was added in PHP 4.3.0.
An optional padding specifier that says
what character will be used for padding the results to the
right string size. This may be a space character or a
0 (zero character). The default is to pad
with spaces. An alternate padding character can be specified
by prefixing it with a single quote (').
See the examples below.
An optional alignment specifier that says
if the result should be left-justified or right-justified.
The default is right-justified; a -
character here will make it left-justified.
An optional number, a width specifier
that says how many characters (minimum) this conversion should
result in.
An optional precision specifier that says
how many decimal digits should be displayed for floating-point
numbers. When using this specifier on a string, it acts as a
cutoff point, setting a maximum character limit to the string.
A type specifier that says what type the
argument data should be treated as. Possible types:
|
% - a literal percent character. No
argument is required.
| |
b - the argument is treated as an
integer, and presented as a binary number.
| |
c - the argument is treated as an
integer, and presented as the character with that ASCII
value.
| |
d - the argument is treated as an
integer, and presented as a (signed) decimal number.
| |
e - the argument is treated as scientific
notation (e.g. 1.2e+2).
| |
u - the argument is treated as an
integer, and presented as an unsigned decimal number.
| |
f - the argument is treated as a
float, and presented as a floating-point number (locale aware).
| |
F - the argument is treated as a
float, and presented as a floating-point number (non-locale aware).
Available since PHP 4.3.10 and PHP 5.0.3.
| |
o - the argument is treated as an
integer, and presented as an octal number.
| |
s - the argument is treated as and
presented as a string.
| |
x - the argument is treated as an integer
and presented as a hexadecimal number (with lowercase
letters).
| |
X - the argument is treated as an integer
and presented as a hexadecimal number (with uppercase
letters).
|
As of PHP 4.0.6 the format string supports argument
numbering/swapping. Here is an example:
Example 1. Argument swapping |
<?php
$format = "There are %d monkeys in the %s";
printf($format, $num, $location);
?>
|
|
This might output, "There are 5 monkeys in the tree". But
imagine we are creating a format string in a separate file,
commonly because we would like to internationalize it and we
rewrite it as:
Example 2. Argument swapping |
<?php
$format = "The %s contains %d monkeys";
printf($format, $num, $location);
?>
|
|
We now have a problem. The order of the placeholders in the
format string does not match the order of the arguments in the
code. We would like to leave the code as is and simply indicate
in the format string which arguments the placeholders refer to.
We would write the format string like this instead:
Example 3. Argument swapping |
<?php
$format = "The %2\$s contains %1\$d monkeys";
printf($format, $num, $location);
?>
|
|
An added benefit here is that you can repeat the placeholders without
adding more arguments in the code. For example:
Example 4. Argument swapping |
<?php
$format = "The %2\$s contains %1\$d monkeys.
That's a nice %2\$s full of %1\$d monkeys.";
printf($format, $num, $location);
?>
|
|
See also printf(),
sscanf(), fscanf(),
vsprintf(), and
number_format().
ExamplesExample 5. printf(): various examples |
<?php
$n = 43951789;
$u = -43951789;
$c = 65; printf("%%b = '%b'\n", $n); printf("%%c = '%c'\n", $c); printf("%%d = '%d'\n", $n); printf("%%e = '%e'\n", $n); printf("%%u = '%u'\n", $n); printf("%%u = '%u'\n", $u); printf("%%f = '%f'\n", $n); printf("%%o = '%o'\n", $n); printf("%%s = '%s'\n", $n); printf("%%x = '%x'\n", $n); printf("%%X = '%X'\n", $n); printf("%%+d = '%+d'\n", $n); printf("%%+d = '%+d'\n", $u); ?>
|
The printout of this program would be:
%b = '10100111101010011010101101'
%c = 'A'
%d = '43951789'
%e = '4.39518e+7'
%u = '43951789'
%u = '4251015507'
%f = '43951789.000000'
%o = '247523255'
%s = '43951789'
%x = '29ea6ad'
%X = '29EA6AD'
%+d = '+43951789'
%+d = '-43951789' |
|
Example 6. printf(): string specifiers |
<?php
$s = 'monkey';
$t = 'many monkeys';
printf("[%s]\n", $s); printf("[%10s]\n", $s); printf("[%-10s]\n", $s); printf("[%010s]\n", $s); printf("[%'#10s]\n", $s); printf("[%10.10s]\n", $t); ?>
|
The printout of this program would be:
[monkey]
[ monkey]
[monkey ]
[0000monkey]
[####monkey]
[many monke] |
|
Example 7. sprintf(): zero-padded integers |
<?php
$isodate = sprintf("%04d-%02d-%02d", $year, $month, $day);
?>
|
|
Example 8. sprintf(): formatting currency |
<?php
$money1 = 68.75;
$money2 = 54.35;
$money = $money1 + $money2;
$formatted = sprintf("%01.2f", $money);
?>
|
|
Example 9. sprintf(): scientific notation |
<?php
$number = 362525200;
echo sprintf("%.3e", $number); ?>
|
|
User Contributed Notes
sprintf
Pacogliss
02-May-2005 02:08
Just a reminder for beginners : example 6 'printf("[%10s]\n", $s);' only works (that is, shows out the spaces) if you put the html '<pre></pre>' tags ( head-scraping time saver ;-).
christian at wenz dot org
18-Apr-2005 02:20
@ henke dot andersson at comhem dot se: Use vprintf()/vsprintf() for that.
henke dot andersson at comhem dot se
15-Apr-2005 10:07
Mind that it doesn't allow you to use a array as multiple arguments like this:
<?php
printf('%s %s',array('a','b')) ?>
downright at comcast dot net
31-Jan-2005 04:03
Just thought I'd give a heads up for anyone doing cross platform applications.
sprintf spacing is different numerically with Windows and Linux.
Linux aligned correctly:
$ol = sprintf ("%-6s|%11.2f|%11.2f|%11.2f|%11.2f|%11.2f|%11.2f|%11.2f|%11.2f\n",
Windows aligned correctly:
$ol = sprintf ("%-6s|%14.2f|%14.2f|%14.2f|%14.2f|%14.2f|%14.2f|%14.2f|%14.2f\n",
As you can see the strings are fine for spacing, however, the numbers need a difference of 3 in order to have the same amount of spaces.
I noticed this after using sprintf to format a header for a web app I was working on. On windows it fit, however, when it came to linux it was MUCH larger than the header.
jrpozo at conclase dot net
21-Jan-2005 09:13
Be careful if you use the %f modifier to round decimal numbers as it (starting from 4.3.10) will no longer produce a float number if you set certain locales, so you can't accumulate the result. For example:
setlocale(LC_ALL, 'es_ES');
echo(sprintf("%.2f", 13.332) + sprintf("%.2f", 14.446))
gives 27 instead of 27.78, so use %F instead.
timo at frenay dot net
10-Jan-2005 12:58
Note that the documentation is unclear about the details of the sign specifier. First of all, the character for this is "+".
Also note that the following does NOT print "+00.00" as you might expect:
<?php
printf('%+02.2f', 0);
?>
The sign is included in the width. This can't be solved by increasing the width:
<?php
printf('%+03.2f', 0);
?>
This will put the padding 0 before the sign.
Here is a possible solution:
<?php
$value = 0;
printf('%s%02.2f', ($value < 0) ? '-' : '+', abs($value));
?>
Gkeeper80
11-Aug-2004 05:58
When using sprintf with padding, it's important to note that specifying the length of your padding does not restrict the length of your output.
For example:
$var = 'test';
$output sprintf("%03s", $var);
print $output;
Produces:
test
NOT:
est
This may seem intuitive for working with numbers, but not neccesarily when working with strings.
rex
15-Jun-2004 04:47
Note, if you are just looking for something to pad out a string consider str_pad.
From testing, it seems faster and was more intuitive to use (for example, making it pad the begining or end of a string... with sprintf you would have to use negative indexes)
php at sharpdreams dot com
08-May-2004 04:13
Note that when using the argument swapping, you MUST number every argument, otherwise sprintf gets confused. This only happens if you use number arguments first, then switch to a non-numbered, and then back to a numbered one.
<?php
$sql = sprintf( "select * from %1\$s left join %2\$s on( %1\$s.id = %2\$s.midpoint ) where %1\$s.name like '%%%s%%' and %2\$s.tagname is not null", "table1", "table2", "bob" );
$sql = sprintf( "select * from %1\$s left join %2\$s on( %1\$s.id = %2\$s.midpoint ) where %1\$s.name like '%%%3\$s%%' and %2\$s.tagname is not null", "table1", "table2", "bob" );
?>
tobias at silverxnet dot de
16-Apr-2004 09:09
Regarding the previous posting:
I just wanted to give an explanation. This should be because the float to string / integer to string conversion (you are using a string, multiplying it with a float value what php automatically causes to convert the string to a float value). This is a general "problem" (or not), but not that hard to explain.
Where an integer or float starts with 0, in a string it does obviously with 1. So if you are using a string your value will increase by one (You started with a string, so it does not increase but contain the real result. If you start using a float value by not using '' around the value, you have to output the float value as well. This is just the PHP conversion.)
Try putting
$x = strval( $x );
after
$x = $x * 100;
and using your example again. You will see that the output will change to 13664 = 13664 because of the general string conversion. It seems that PHP is converting a float to a string by inceasing by one. By doing the same with intval instead of strval the output changes to 13663 = 13663.
! sprintf seems to behave wrong when using the conversation to an integer value and NOT doing the conversation at all. So use intval to convert to an integer value or strval to convert to a string value BEFORE using sprintf. This should be solving the problems.
kekec at kukac dot hu
29-Mar-2004 11:16
A really working one:
<?php
function cutzero($value) {
return preg_replace("/(\.?)0+$/", "", $value);
}
?>
05-Mar-2004 12:54
both of your cut-zero functions are just way too complicated. if it's a string where only the zeros at the end should be truncated, why not use a syntax as simple as rtrim("4.7000","0") ?
martin at schwedes dot com
09-Jul-2003 05:45
decision within sprintf:
$a = "today";
$b = sprintf('This is %s', $a=='today' ? 'today':'not today');
echo $b;
// result: This is today
Rene dot Leonhardt at agritec24 dot com
16-May-2003 12:02
Your cutzero function could be faster ;-)
return (double)$value;
But if you must have a function:
return preg_replace('/0+$/', '', $value);
kouber at php dot net
08-May-2003 04:55
If you want to cut all the zeros off the end of a float, but not losing any sensitive information, use this:
<?
function cutzero($value) {
return preg_replace("/(\.\d+?)0+$/", "$1", $value)*1;
}
?>
Some examples:
<?
cutzero("4.7600"); cutzero("4.7604") cutzero("4.7000"); cutzero("4.0000"); ?>
info at nospam dot webtip dot dk
18-Feb-2003 07:06
If you want to format a phonenumber with spaces, use chunk_split() which splits a string into smaller chunks. It's much simpler than using sprintf.
$phone = "12345678";
chunk_split ($phone, 2);
will return 12 34 56 78
moritz dot geselle at invision-team dot de
02-Dec-2002 04:52
a little note to the argument swapping examples which took me a while to get:
if you use single quotes for the format string (like you should do, since there aren't any variable conversions to do as long as you don't need any special chars), the given examples won't work because of the backslash before the $ (needs to be escaped in double quoted strings - but not in single quoted!)
so this:
$format = "The %2\$s contains %1\$d monkeys";
printf($format,$num,$location);
with a single quoted format string would look like this:
$format = 'The %2$s contains %1$d monkeys';
printf($format,$num,$location);
(no escapes)
I hope that helps to avoid confusion ;)
no dot email dot address at example dot com
16-Sep-2002 08:29
Using argument swapping in sprintf() with gettext: Let's say you've written the following script:
<?php
$var = sprintf(gettext("The %2\$s contains %1\$d monkeys"), 2, "cage");
?>
Now you run xgettext in order to generate a .po file. The .po file will then look like this:
#: file.php:9
#, ycp-format
msgid "The %2\\$s contains %1\\$d monkeys"
msgstr ""
Notice how an extra backslash has been added by xgettext.
Once you've translated the string, you must remove all backslashes from the ID string as well as the translation, so the po file will look like this:
#: file.php:9
#, ycp-format
msgid "The %2$s contains %1$d monkeys"
msgstr "Der er %1$d aber i %2$s"
Now run msgfmt to generate the .mo file, restart Apache to remove the gettext cache if necessary, and you're off.
abiltcliffe at bigfoot.com
10-Sep-2002 01:01
To jrust at rustyparts.com, note that if you're using a double-quoted string and *don't* escape the dollar sign with a backslash, $s and $d will be interpreted as variable references. The backslash isn't part of the format specifier itself but you do need to include it when you write the format string (unless you use single quotes).
Andrew dot Wright at spamsux dot atnf dot csiro dot au
03-Jul-2002 04:22
An error in my last example:
$b = sprintf("%30.s", $a);
will only add enough spaces before $a to pad the spaces + strlen($a) to 30 places.
My method of centering fixed text in a 72 character width space is:
$a = "Some string here";
$lwidth = 36; // 72/2
$b = sprintf("%".($lwidth + round(strlen($a)/2)).".s", $a);
eden_zero_x at hotmail dot com
26-Jun-2002 04:05
Well I came up with this one, extremely simple. instead of writing <span class="class">hello</a>
you can write: print class('class','hello'); using sprintf
-----------------------------
function class_ ($class, $text=false)
{
return sprintf ("<span class=\"%s\">%s</span>",
$class,
($text ? $text : $class)
);
}
-----------------------------
shgyn at binabakti dot or dot id
01-Jun-2002 09:57
Previously submitted sci() function to get scientific representation of a number is not working with 0 and negative numbers. So, here is the modified version:
function sci($x, $d=-1) {
$min=($x<0)?"-":"";
$x=abs($x);
$e=floor(($x!=0)?log10($x):0);
$x*=pow(10,-$e);
$fmt=($d>=0)?".".$d:"";
$e=($e>=0)?"+".sprintf("%02d",$e):"-".sprintf("%02d",-$e);
return sprintf("$min%".$fmt."fe%s",$x,$e);
}
fuchschr at surfeu dot at
20-Feb-2002 10:54
To have a string with leading zeros use this:
$string_i = sprintf("%04s",$value)
Gives you an output with leading zeros and 4 digits.
i.e.
0001
0002
...
0010
an so on
cv at corbach dot de
10-Feb-2002 09:36
To make radu.rendec@ines.ro's excellent function work on signed numbers you must change the first line to:
$e = floor(log10(abs($x)));
radu dot rendec at ines dot ro
09-Jan-2002 08:49
The 'e' format specifier is not documented. However, it seems to work, but without showing the exponential part of the number.
This is a function to get the scientific representation of a number:
function sci($x, $d=-1) {
$e=floor(log10($x));
$x*=pow(10,-$e);
$fmt=($d>=0)?".".$d:"";
$e=($e>=0)?"+".sprintf("%02d",$e):"-".sprintf("%02d",-$e);
return sprintf("%".$fmt."fe%s",$x,$e);
}
It takes the number as the first parameter and the precision as the second. The precision is optional. The default precision for the 'f' format specifier is used if no precision is specified.
anqmb(at)yahoo.co.jp
05-Dec-2001 06:51
Watch out the mysterious rounding rule.
<?php
$a = 4.5;
$b = sprintf("%d",$a);
$c = 4.5;
$d = sprintf("%.0f",$c);
$e = 0.45;
$f = sprintf("%.1f",$e);
print ("$b,$d,$f\n");
?>
The code above prints "4,5,0.5".
(Perl version prints "4,4,0.5".)
keeper at odi dot com dot br
26-Nov-2001 11:26
Took me a while to find this out.
hope will save someones time.
IT ADD A CARACRER TO THE END OF A STRING
$x = sprintf("%'x-10s", "a");
echo $x;
target_rex at hotmail dot com
14-Apr-2001 09:20
$a = 5;
// $a is a int
echo $5;
// Outputs:"5";
// If you would like to print $a as a bin,(101) like: 00000101 (8 digits)
sprintf("%8b", $a) // Witch returns exatly 00000101 (8 digits)
// My function looked like:
//////////////////////////////////////////
// By DrRex - www.DrRex.dk - 15/04-2001 //
// string bin(int dec) //
//////////////////////////////////////////
function bin($dec){
$bin = sprintf("%8b", $dec);
return $bin;
}
//////////////////////////////////////////
// Very short exampels how to use bin()
echo "\n1. 128(10) == ".bin(128)."(2)";
$hits = 100;
echo "\n2. Loaded ".bin($hits)."(2) times! Bib!";
// Not very usefull, nobody understands the number, exept if small counters like this one. If it wasn't 8(2) but FFFFFF(16) digits. I would give up...
// This would output:
1. 128(10) == 10000000(2)
2. Loaded 01100100(2) times! Bib!
-------------------------------------------------
Greetings from Christiania, Copenhagen, Denmark!
All code by DrRex
www.DrRex.dk
tjchamberlain.hotmail@com
26-Mar-2001 01:16
It is worth noting that "%5.2f" will result in a string 8 characters long (5 then the '.' then 2), not 5 characters as you might expect.
prolixmp3 at navigators dot lv
23-Mar-2001 12:55
If you are going to create a counter which uses _symbols_ before actual digits (see, f.e., SpyLog.com counters - they are filling space with "." before, so the count like 12345 looks like "........12345"), you can use the following:
$txt = "Abracadabra"; // actual string
$fit = 16; // how many digits to use
$fill = "."; // what to fill
$digits = sprintf ("%'{$fill}{$fit}s", $txt);
Paul (a.k.a. Mr.Prolix)
voudras at nospam dot swiftslayer dot org
17-Nov-2000 08:58
Little note about sprintf and its ilk.
if you attempt something like
$string = "dingy%sflem%dwombat";
$nbr = 5;
$name = "voudras";
$msg = sprintf("%d $string %s", $nbr, $name);
sprintf will complain about a lack in the number of arguments, this would be because of the %'s in the actual string. This can be a great benifit, but is also rather confusing if you dont realize this feature, and are passing questionable variables to sprintf (for, say perhaps logging). One way around this is using
ereg_replace("%","%%", $string); before
sending it off to sprintf. This is actually how i came across this as a problem - i had realized some time ago that i would have to test my $string for
%'s, but when running the %->%% replacement on a very large serialized object, my application timed out.
My solution was to use
sprintf("%d %s %s", $nbr, $string, $name);
but, there was a reason i originally had done this the other way - i suppose i'll find out soon enough
paolini at kahuna dot sdsu dot edu
14-Apr-1999 03:12
Hey folks, don't forget to prefix a precision specifier with a period '.'!
Thus, to print a floating point number,
say $x, with two digits after the decimal point you would write:
printf( "%.2f", $x );
| |