©
本文档使用 PHP中文网手册 发布
(PHP 4, PHP 5)
sprintf — Return a formatted string
$format
[, mixed $args
[, mixed $...
]] )
Returns a string produced according to the formatting string
format
.
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:
A type specifier that says what type the argument data should be treated as. Possible types:
Variables will be co-erced to a suitable type for the specifier:
Type | Specifiers |
---|---|
string | s |
integer | d, u, c, o, x, X, b |
double | g, G, e, E, f, F |
Attempting to use a combination of the string and width specifiers with character sets that require more than one byte per character may result in unexpected results
The format string supports argument numbering/swapping. Here is an example:
Example #1 Argument swapping
<?php
$num = 5 ;
$location = 'tree' ;
$format = 'There are %d monkeys in the %s' ;
echo sprintf ( $format , $num , $location );
?>
Example #2 Argument swapping
<?php
$format = 'The %s contains %d monkeys' ;
echo sprintf ( $format , $num , $location );
?>
Example #3 Argument swapping
<?php
$format = 'The %2$s contains %1$d monkeys' ;
echo sprintf ( $format , $num , $location );
?>
Example #4 Argument swapping
<?php
$format = 'The %2$s contains %1$d monkeys.
That\'s a nice %2$s full of %1$d monkeys.' ;
echo sprintf ( $format , $num , $location );
?>
Example #5 Specifying padding character
<?php
echo sprintf ( "%'.9d\n" , 123 );
echo sprintf ( "%'.09d\n" , 123 );
?>
以上例程会输出:
......123 000000123
Example #6 Position specifier with other specifiers
<?php
$format = 'The %2$s contains %1$04d monkeys' ;
echo sprintf ( $format , $num , $location );
?>
以上例程会输出:
The tree contains 0005 monkeys
Note:
Attempting to use a position specifier greater than
PHP_INT_MAX
will result in sprintf() generating warnings.
The c type specifier ignores padding and width
args
...
Returns a string produced according to the formatting string
format
.
Example #7 printf() : various examples
<?php
$n = 43951789 ;
$u = - 43951789 ;
$c = 65 ; // ASCII 65 is 'A'
// notice the double %%, this prints a literal '%' character
printf ( "%%b = '%b'\n" , $n ); // binary representation
printf ( "%%c = '%c'\n" , $c ); // print the ascii character, same as chr() function
printf ( "%%d = '%d'\n" , $n ); // standard integer representation
printf ( "%%e = '%e'\n" , $n ); // scientific notation
printf ( "%%u = '%u'\n" , $n ); // unsigned integer representation of a positive integer
printf ( "%%u = '%u'\n" , $u ); // unsigned integer representation of a negative integer
printf ( "%%f = '%f'\n" , $n ); // floating point representation
printf ( "%%o = '%o'\n" , $n ); // octal representation
printf ( "%%s = '%s'\n" , $n ); // string representation
printf ( "%%x = '%x'\n" , $n ); // hexadecimal representation (lower-case)
printf ( "%%X = '%X'\n" , $n ); // hexadecimal representation (upper-case)
printf ( "%%+d = '%+d'\n" , $n ); // sign specifier on a positive integer
printf ( "%%+d = '%+d'\n" , $u ); // sign specifier on a negative integer
?>
以上例程会输出:
%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 #8 printf() : string specifiers
<?php
$s = 'monkey' ;
$t = 'many monkeys' ;
printf ( "[%s]\n" , $s ); // standard string output
printf ( "[%10s]\n" , $s ); // right-justification with spaces
printf ( "[%-10s]\n" , $s ); // left-justification with spaces
printf ( "[%010s]\n" , $s ); // zero-padding works on strings too
printf ( "[%'#10s]\n" , $s ); // use the custom padding character '#'
printf ( "[%10.10s]\n" , $t ); // left-justification but with a cutoff of 10 characters
?>
以上例程会输出:
[monkey] [ monkey] [monkey ] [0000monkey] [####monkey] [many monke]
Example #9 sprintf() : zero-padded integers
<?php
$isodate = sprintf ( "%04d-%02d-%02d" , $year , $month , $day );
?>
Example #10 sprintf() : formatting currency
<?php
$money1 = 68.75 ;
$money2 = 54.35 ;
$money = $money1 + $money2 ;
// echo $money will output "123.1";
$formatted = sprintf ( "%01.2f" , $money );
// echo $formatted will output "123.10"
?>
Example #11 sprintf() : scientific notation
<?php
$number = 362525200 ;
echo sprintf ( "%.3e" , $number ); // outputs 3.625e+8
?>
[#1] Sam Bull [2015-10-23 14:35:21]
Fix for sprintfn function for named arguments (http://php.net/manual/en/function.sprintf.php#94608):
Change the first line from:
$arg_nums = array_slice(array_flip(array_keys(array(0 => 0) + $args)), 1);
to:
$arg_nums = array_keys($args);
array_unshift($arg_nums, 0);
$arg_nums = array_flip(array_slice($arg_nums, 1, NULL, true));
[#2] nmmm at nmmm dot nu [2015-04-08 07:31:34]
php printf and sprintf not seems to support star "*" formatting.
here is an example:
printf("%*d\n",3,5);
this will print just "d" instead of "<two spaces>5"
[#3] kontakt at myseosolution dot de [2015-02-26 10:34:30]
There are already some comments on using sprintf to force leading leading zeros but the examples only include integers. I needed leading zeros on floating point numbers and was surprised that it didn't work as expected.
Example:
<?php
sprintf('%02d', 1);
?>
This will result in 01. However, trying the same for a float with precision doesn't work:
<?php
sprintf('%02.2f', 1);
?>
Yields 1.00.
This threw me a little off. To get the desired result, one needs to add the precision (2) and the length of the decimal seperator "." (1). So the correct pattern would be
<?php
sprintf('%05.2f', 1);
?>
Output: 01.00
Please see http://stackoverflow.com/a/28739819/413531 for a more detailed explanation.
[#4] sanjay dot chawke at gmail dot com [2015-01-15 11:10:03]
sprintf("SELECT * FROM event WHERE event_date >= NOW() and event_id =%d %s GROUP BY event_id ",filter())
function filter($condition=''){
global $keyword;
if(!empty($keyword)){
$condition =" AND event_name LIKE '%$keyword%'";
}
return $condition;
}
[#5] john at jbwalker dot com [2014-05-24 00:24:27]
I couldn't find what should be a WARNING in the documentation above, that if you have more specifiers than variables to match them sprintf returns NOTHING. This fact, IMHO, should also be noted under return values.
[#6] hdimac at gmail dot com [2014-04-14 16:00:38]
In the examples, is being shown printf, but it should say sprintf, which is the function being explained... just a simple edition mistake.
[#7] ivan at php dot net [2013-12-28 20:13:48]
There is a minor issue in a code of mb_vsprintf function from viktor at textalk dot com.
In "truncate $arg" section the following line:
$arg = mb_substr($precision,0,$precision,$encoding);
needs to be replaced with:
$arg = mb_substr($arg,0,$precision,$encoding);
[#8] ethaizone at hotmail dot com [2013-10-24 03:52:16]
Example: use sprintf to zero fill
<?php
// 00000005
echo sprintf('%08d', 5);
[#9] me at php dot net [2013-06-30 17:51:29]
To convert / use / implement 64-bit signed 2's complement Long type values in PHP code, use the following code
// requires bcmath
bcscale(0);
$num = substr($data,0,8) // 8 binary bytes from file
$long = bcadd(bcmul(unpack('N',substr($num,0,4))[1],bcpow(2,32)),unpack('N',substr($num,4,4))[1]);
if(unpack('N',substr($num,4,4))[1] & 0x80000000)
$long = bcadd($long,pow(2,32));
var_dump($long);
// now you can use $long as 64-bit signed long value by using bcmath functions
// do not use php math funcs, they cant handle 64-bit long integer values
// use bcadd bcsub etc from bcmath functions freely
Hope this helps people handling 64-bit long values retrieved from other languages like java, etc
[#10] Alex R. Gibbs [2013-01-25 08:17:00]
1. A plus sign ('+') means put a '+' before positive numbers while a minus sign ('-') means left justify. The documentation incorrectly states that they are interchangeable. They produce unique results that can be combined:
<?php
echo sprintf ("|%+4d|%+4d|\n", 1, -1);
echo sprintf ("|%-4d|%-4d|\n", 1, -1);
echo sprintf ("|%+-4d|%+-4d|\n", 1, -1);
?>
outputs:
| +1| -1|
|1 |-1 |
|+1 |-1 |
2. Padding with a '0' is different than padding with other characters. Zeros will only be added at the front of a number, after any sign. Other characters will be added before the sign, or after the number:
<?php
echo sprintf ("|%04d|\n", -2);
echo sprintf ("|%':4d|\n", -2);
echo sprintf ("|%-':4d|\n", -2);
// Specifying both "-" and "0" creates a conflict with unexpected results:
echo sprintf ("|%-04d|\n", -2);
// Padding with other digits behaves like other non-zero characters:
echo sprintf ("|%-'14d|\n", -2);
echo sprintf ("|%-'04d|\n", -2);
?>
outputs:
|-002|
|::-2|
|-2::|
|-2 |
|-211|
|-2 |
[#11] ignat dot scheglovskiy at gmail dot com [2012-10-10 20:47:31]
Here is an example how alignment, padding and precision specifier can be used to print formatted list of items:
<?php
$out = "The Books\n";
$books = array("Book 1", "Book 2", "Book 3");
$pages = array("123 pages ", "234 pages", "345 pages");
for ($i = 0; $i < count($books); $i++) {
$out .= sprintf("%'.-20s%'.7.4s\n", $books[$i], $pages[$i]);
}
echo $out;
// Outputs:
//
// The Books
// Book 1.................123
// Book 2.................234
// Book 3.................345
?>
[#12] Hayley Watson [2012-06-07 11:21:04]
If you use argument numbering, then format specifications with the same number get the same argument; this can save repeating the argument in the function call.
<?php
$pattern = '%1$s %1$\'#10s %1$s!';
printf($pattern, "badgers");
?>
[#13] krzysiek dot 333 at gmail dot com - zryty dot hekko dot pl [2011-08-20 00:48:03]
Encoding and decoding IP adress to format: 1A2B3C4D (mysql column: char(8) )
<?php
function encode_ip($dotquad_ip)
{
$ip_sep = explode('.', $dotquad_ip);
return sprintf('%02x%02x%02x%02x', $ip_sep[0], $ip_sep[1], $ip_sep[2], $ip_sep[3]);
}
function decode_ip($int_ip)
{
$hexipbang = explode('.', chunk_split($int_ip, 2, '.'));
return hexdec($hexipbang[0]). '.' . hexdec($hexipbang[1]) . '.' . hexdec($hexipbang[2]) . '.' . hexdec($hexipbang[3]);
}
?>
[#14] timo dot frenay at gmail dot com [2011-05-02 05:38:37]
Here is how to print a floating point number with 16 significant digits regardless of magnitude:
<?php
$result = sprintf(sprintf('%%.%dF', max(15 - floor(log10($value)), 0)), $value);
?>
This works more reliably than doing something like sprintf('%.15F', $value) as the latter may cut off significant digits for very small numbers, or prints bogus digits (meaning extra digits beyond what can reliably be represented in a floating point number) for very large numbers.
[#15] carmageddon at gmail dot com [2011-02-02 06:38:25]
If you want to convert a decimal (integer) number into constant length binary number in lets say 9 bits, use this:
$binary = sprintf('%08b', $number );
for example:
<?php
$bin = sprintf('%08b',511 );
echo $bin."\n";
?>
would output 111111111
And 2 would output 00000010
I know the leading zeros are useful to me, perhaps they are to someone else too.
[#16] dwieeb at gmail dot com [2010-09-01 11:54:47]
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
//Here is the function:
function sprintf_nbsp() {
$args = func_get_args();
return str_replace(' ', ' ', vsprintf(array_shift($args), array_values($args)));
}
//Usage (exactly like sprintf):
$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
//The variation that prints the string instead of returning it:
function printf_nbsp() {
$args = func_get_args();
echo str_replace(' ', ' ', vsprintf(array_shift($args), array_values($args)));
}
?>
[#17] geertdd at gmail dot com [2010-09-01 00:53:48]
Note that when using a sign specifier, the number zero is considered positive and a "+" sign will be prepended to it.
<?php
printf('%+d', 0); // +0
?>
[#18] nate at frickenate dot com [2009-11-13 23:45:40]
Here's a clean, working version of functions to allow using named arguments instead of numeric ones. ex: instead of sprintf('%1$s', 'Joe');, we can use sprintf('%name$s', array('name' => 'Joe'));. I've provided 2 different versions: the first uses the php-like syntax (ex: %name$s), while the second uses the python syntax (ex: %(name)s).
<?php
function sprintfn ($format, array $args = array()) {
// map of argument names to their corresponding sprintf numeric argument value
$arg_nums = array_slice(array_flip(array_keys(array(0 => 0) + $args)), 1);
// find the next named argument. each search starts at the end of the previous replacement.
for ($pos = 0; preg_match('/(?<=%)([a-zA-Z_]\w*)(?=\$)/', $format, $match, PREG_OFFSET_CAPTURE, $pos);) {
$arg_pos = $match[0][1];
$arg_len = strlen($match[0][0]);
$arg_key = $match[1][0];
// programmer did not supply a value for the named argument found in the format string
if (! array_key_exists($arg_key, $arg_nums)) {
user_error("sprintfn(): Missing argument '${arg_key}'", E_USER_WARNING);
return false;
}
// replace the named argument with the corresponding numeric one
$format = substr_replace($format, $replace = $arg_nums[$arg_key], $arg_pos, $arg_len);
$pos = $arg_pos + strlen($replace); // skip to end of replacement for next iteration
}
return vsprintf($format, array_values($args));
}
function sprintfn ($format, array $args = array()) {
// map of argument names to their corresponding sprintf numeric argument value
$arg_nums = array_slice(array_flip(array_keys(array(0 => 0) + $args)), 1);
// find the next named argument. each search starts at the end of the previous replacement.
for ($pos = 0; preg_match('/(?<=%)\(([a-zA-Z_]\w*)\)/', $format, $match, PREG_OFFSET_CAPTURE, $pos);) {
$arg_pos = $match[0][1];
$arg_len = strlen($match[0][0]);
$arg_key = $match[1][0];
// programmer did not supply a value for the named argument found in the format string
if (! array_key_exists($arg_key, $arg_nums)) {
user_error("sprintfn(): Missing argument '${arg_key}'", E_USER_WARNING);
return false;
}
// replace the named argument with the corresponding numeric one
$format = substr_replace($format, $replace = $arg_nums[$arg_key] . '$', $arg_pos, $arg_len);
$pos = $arg_pos + strlen($replace); // skip to end of replacement for next iteration
}
return vsprintf($format, array_values($args));
}
?>
[#19] Astone [2009-09-15 23:41:45]
When you're using Google translator, you have to 'escape' the 'conversion specifications' by putting <span class="notranslate"></span> around them.
Like this:
<?php
function getGoogleTranslation($sString, $bEscapeParams = true)
{
// "escape" sprintf paramerters
if ($bEscapeParams)
{
$sPatern = '/(?:%%|%(?:[0-9]+\$)?[+-]?(?:[ 0]|\'.)?-?[0-9]*(?:\.[0-9]+)?[bcdeufFosxX])/';
$sEscapeString = '<span class="notranslate">$0</span>';
$sString = preg_replace($sPatern, $sEscapeString, $sString);
}
// Compose data array (English to Dutch)
$aData = array(
'v' => '1.0',
'q' => $sString,
'langpair' => 'en|nl',
);
// Initialize connection
$rService = curl_init();
// Connection settings
curl_setopt($rService, CURLOPT_URL, 'http://ajax.googleapis.com/ajax/services/language/translate');
curl_setopt($rService, CURLOPT_RETURNTRANSFER, true);
curl_setopt($rService, CURLOPT_POSTFIELDS, $aData);
// Execute request
$sResponse = curl_exec($rService);
// Close connection
curl_close($rService);
// Extract text from JSON response
$oResponse = json_decode($sResponse);
if (isset($oResponse->responseData->translatedText))
{
$sTranslation = $oResponse->responseData->translatedText;
}
else
{
// If some error occured, use the original string
$sTranslation = $sString;
}
// Replace "notranslate" tags
if ($bEscapeParams)
{
$sEscapePatern = '/<span class="notranslate">([^<]*)<\/span>/';
$sTranslation = preg_replace($sEscapePatern, '$1', $sTranslation);
}
// Return result
return $sTranslation;
}
?>
Thanks to MelTraX for defining the RegExp!
[#20] Jay Gilford [2009-08-25 17:13:38]
I created this function a while back to save on having to combine mysql_real_escape_string onto all the params passed into a sprintf. it works literally the same as the sprintf other than that it doesn't require you to escape your inputs. Hope its of some use to people
<?php
function mressf()
{
$args = func_get_args();
if (count($args) < 2)
return false;
$query = array_shift($args);
$args = array_map('mysql_real_escape_string', $args);
array_unshift($args, $query);
$query = call_user_func_array('sprintf', $args);
return $query;
}
?>
Regards
Jay
Jaygilford.com
[#21] jfgrissom at gmail dot com [2009-07-11 21:51:49]
I had a nightmare trying to find the two's complement of a 32 bit number.
I got this from http://www.webmasterworld.com/forum88/13334.htm (credit where credit is due... =P )
Quote: ...find out the 2's complement of any number, which is -(pow(2, n) - N) where n is the number of bits and N is the number for which to find out its 2's complement.
This worked magic for me... previously I was trying to use
sprintf ("%b",$32BitDecimal);
But it always returned 10000000000000000000000 when the $32BitDecimal value got above 2,000,000,000.
This -(pow(2, n) - N)
Worked remarkably well and was very accurate.
Hope this helps someone fighting with two's complement in PHP.
[#22] John Walker [2009-07-09 17:56:38]
To add to other notes below about floating point problems, I noted that %f and %F will apparently output a maximum precision of 6 as a default so you have to specify 1.15f (eg) if you need more.
In my case, the input (from MySQL) was a string with 15 digits of precision that was displayed with 6. Likely what happens is that the rounding occurs in the conversion to a float before it is displayed. Displaying it as 1.15f (or in my case, %s) shows the correct number.
[#23] viktor at textalk dot com [2009-02-18 08:16:57]
A more complete and working version of mb_sprintf and mb_vsprintf. It should work with any "ASCII preserving" encoding such as UTF-8 and all the ISO-8859 charsets. It handles sign, padding, alignment, width and precision. Argument swapping is not handled.
<?php
if (!function_exists('mb_sprintf')) {
function mb_sprintf($format) {
$argv = func_get_args() ;
array_shift($argv) ;
return mb_vsprintf($format, $argv) ;
}
}
if (!function_exists('mb_vsprintf')) {
function mb_vsprintf($format, $argv, $encoding=null) {
if (is_null($encoding))
$encoding = mb_internal_encoding();
// Use UTF-8 in the format so we can use the u flag in preg_split
$format = mb_convert_encoding($format, 'UTF-8', $encoding);
$newformat = ""; // build a new format in UTF-8
$newargv = array(); // unhandled args in unchanged encoding
while ($format !== "") {
// Split the format in two parts: $pre and $post by the first %-directive
// We get also the matched groups
list ($pre, $sign, $filler, $align, $size, $precision, $type, $post) =
preg_split("!\%(\+?)('.|[0 ]|)(-?)([1-9][0-9]*|)(\.[1-9][0-9]*|)([%a-zA-Z])!u",
$format, 2, PREG_SPLIT_DELIM_CAPTURE) ;
$newformat .= mb_convert_encoding($pre, $encoding, 'UTF-8');
if ($type == '') {
// didn't match. do nothing. this is the last iteration.
}
elseif ($type == '%') {
// an escaped %
$newformat .= '%%';
}
elseif ($type == 's') {
$arg = array_shift($argv);
$arg = mb_convert_encoding($arg, 'UTF-8', $encoding);
$padding_pre = '';
$padding_post = '';
// truncate $arg
if ($precision !== '') {
$precision = intval(substr($precision,1));
if ($precision > 0 && mb_strlen($arg,$encoding) > $precision)
$arg = mb_substr($precision,0,$precision,$encoding);
}
// define padding
if ($size > 0) {
$arglen = mb_strlen($arg, $encoding);
if ($arglen < $size) {
if($filler==='')
$filler = ' ';
if ($align == '-')
$padding_post = str_repeat($filler, $size - $arglen);
else
$padding_pre = str_repeat($filler, $size - $arglen);
}
}
// escape % and pass it forward
$newformat .= $padding_pre . str_replace('%', '%%', $arg) . $padding_post;
}
else {
// another type, pass forward
$newformat .= "%$sign$filler$align$size$precision$type";
$newargv[] = array_shift($argv);
}
$format = strval($post);
}
// Convert new format back from UTF-8 to the original encoding
$newformat = mb_convert_encoding($newformat, $encoding, 'UTF-8');
return vsprintf($newformat, $newargv);
}
}
?>
[#24] splogamurugan at gmail dot com [2009-02-06 05:59:04]
$format = 'There are %1$d monkeys in the %s and %s ';
printf($format, 100, 'Chennai', 'Bangalore');
Expecting to output
"There are 100 monkeys in the Chennai and bangalore"
But, this will output
"There are 100 monkeys in the 100 and Chennai"
Because, the second and Third specifiers takes 1rst and 2nd arguments. Because it is not assigned with any arguments.
[#25] remy dot damour at -please-no-spam-laposte dot net [2009-01-15 11:15:28]
With printf() and sprintf() functions, escape character is not backslash '\' but rather '%'.
Ie. to print '%' character you need to escape it with itself:
<?php
printf('%%%s%%', 'koko'); #output: '%koko%'
?>
[#26] MelTraX [2008-11-05 13:40:22]
<?php
// parses a string meant for printf and returns an array of found parameters (or NULL if it contains syntax errors)
function parsePrintfParameters($string) {
$valid = '/^(?:%%|%(?:[0-9]+\$)?[+-]?(?:[ 0]|\'.)?-?[0-9]*(?:\.[0-9]+)?[bcdeufFosxX])/';
$originalString = $string;
$result = array();
while(strlen($string)) {
if(!$string = preg_replace('/^[^%]*/', '', $string))
break;
if(preg_match($valid, $string, $matches)) {
$result[] = $matches[0];
$string = substr($string, strlen($matches[0]));
} else {
error(sprintf('"%s" has an error near "%s".', $originalString, $string));
return NULL;
}
}
return $result;
}
?>
[#27] php at mikeboers dot com [2008-10-01 13:42:54]
And continuing on the same theme of a key-based sprintf...
I'm roughly (I can see a couple cases where it comes out wierd) copying the syntax of Python's string formatting with a dictionary. The improvement over the several past attempts is that this one still respects all of the formating options, as you can see in my example.
And the error handling is really crappy (just an echo). I just threw this together so do with it what you will. =]
<?php
function sprintf_array($string, $array)
{
$keys = array_keys($array);
$keysmap = array_flip($keys);
$values = array_values($array);
while (preg_match('/%\(([a-zA-Z0-9_ -]+)\)/', $string, $m))
{
if (!isset($keysmap[$m[1]]))
{
echo "No key $m[1]\n";
return false;
}
$string = str_replace($m[0], '%' . ($keysmap[$m[1]] + 1) . '$', $string);
}
array_unshift($values, $string);
var_dump($values);
return call_user_func_array('sprintf', $values);
}
echo sprintf_array('4 digit padded number: %(num)04d ', array('num' => 42));
?>
Cheers!
[#28] ant at loadtrax dot com [2008-06-18 02:19:45]
Rounding seems a little inconsistent, so beware:
$ php -a
php> print round(1.0*20*1.175/100,2);
0.24
php > print sprintf("%.2f",1.0*20*1.175/100);
0.23
php > print sprintf("%.0f",1.0*20*1.175);
24
I get round this by doing the round first, then doing the sprintf.
[#29] jaimthorn at yahoo dot com [2008-06-11 07:01:19]
I needed a piece of code similar to the one Matt posted below, on the 10th of March, 2008. However, I wasn't completely satisfied with Matt's code (sorry, Matt! No offense intended!), because
1) I don't like to initialize variables when it's not really needed, and
2) it contains two bugs.
What are the bugs?
First, Matt's code tests for count($vars) > 0, but if $var == "Hello world!", then count($var) == 1, but the foreach() will crash because $var has to be an array. So instead, my code tests for is_array($var).
Second, if a key in $vars is a prefix of any of the later keys in the array (like 'object' is the beginning of 'objective') then the str_replace messes things up. This is no big deal if your keys are hard-coded and you can make sure the keys don't interfere, but in my code the keys are variable. So I decided to first sort the array on a decreasing length of the key.
<?php
function cmp($a, $b)
{
return strlen($b) - strlen($a);
}
function sprintf2($str, $vars, $char = '%')
{
if(is_array($vars))
{
uksort($vars, "cmp");
foreach($vars as $k => $v)
{
$str = str_replace($char . $k, $v, $str);
}
}
return $str;
}
echo sprintf2( 'Hello %your_name, my name is %my_name! I am %my_age, how old are you? I like %object and I want to %objective_in_life!'
, array( 'your_name' => 'Matt'
, 'my_name' => 'Jim'
, 'my_age' => 'old'
, 'object' => 'women'
, 'objective_in_life' => 'write code'
)
);
?>
If possible, and if you're willing, you can also embed the key fields in the text between percent-signs, rather than prefixing the keys with one. Sorting is no longer necessary, and the execution time is less than half of the code above:
<?php
function sprintf3($str, $vars, $char = '%')
{
$tmp = array();
foreach($vars as $k => $v)
{
$tmp[$char . $k . $char] = $v;
}
return str_replace(array_keys($tmp), array_values($tmp), $str);
}
echo sprintf3( 'Hello %your_name%, my name is %my_name%! I am %my_age%, how old are you? I like %object% and I want to %objective_in_life%!'
, array( 'your_name' => 'Matt'
, 'my_name' => 'Jim'
, 'my_age' => 'old'
, 'object' => 'women'
, 'objective_in_life' => 'write code'
)
);
?>
If you're willing to embed the keys in the text, you may also be willing to embed the keys themselves in percent signs, thus shaving off another 30% of the execution time:
<?php
function sprintf4($str, $vars)
{
return str_replace(array_keys($vars), array_values($vars), $str);
}
echo sprintf4( 'Hello %your_name%, my name is %my_name%! I am %my_age%, how old are you? I like %object% and I want to %objective_in_life%!'
, array( '%your_name%' => 'Matt'
, '%my_name%' => 'Jim'
, '%my_age%' => 'old'
, '%object%' => 'women'
, '%objective_in_life%' => 'write code'
)
);
?>
Of course, by now the sprintf function is no longer something you'd want to write to mum and dad about...
[#30] ranema at ubuntu dot polarhome dot com [2008-03-30 07:40:49]
It's very comfortible for long Sql queries:
<?php
$_gQuery = "UPDATE `x` SET `a` = %i AND `b` = '%s' WHERE `my` = '%s';"; // ........
mysql_query( sprintf( $_gQuery, 10, 'a', 'rrrr' ) );
?>
But if you have a short query, then it would be much faster to append your data by using `.`.
<?php
$_gQuery = 'SELECT COUNT(*) FROM `' . $_gName . '`;';
?>
[#31] matt [2008-03-10 09:13:16]
Was looking for a assoc way of using sprintf but couldnt find one, probably wasnt looking hard enough so came up with this. Very very simple indeed...
<?php
function sprintf2($str='', $vars=array(), $char='%')
{
if (!$str) return '';
if (count($vars) > 0)
{
foreach ($vars as $k => $v)
{
$str = str_replace($char . $k, $v, $str);
}
}
return $str;
}
echo sprintf2('Hello %your_name my name is %my_name! I am %my_age, how old are you? I like %object!', array(
'your_name' => 'Ben',
'my_name' => 'Matt',
'my_age' => '21',
'object' => 'food'
));
// Hello Ben my name is Matt! I am 21, how old are you? I like food!
?>
Looks nice anyway :)
[#32] scott dot gardner at mac dot com [2008-01-10 13:22:18]
In the last example of Example#6, there is an error regarding the output.
printf("[%10.10s]\n", $t); // left-justification but with a cutoff of 10 characters
This outputs right-justified.
In order to output left-justified:
printf("[%-10.10s]\n", $t);
[#33] me at umarfarooq dot net [2007-09-06 23:29:21]
function formatString($string, $len)
{
if (strlen($string) < $len)
{
$addchar=($len - strlen($string)) ;
for ($i = 0; $i < $addchar; $i++)
{
$string=sprintf("$string%s", "0");
}
}
if (strlen($string) > $len)
{
$string=substr($string,0,$len);
}
return $string;
}
[#34] Thomas Breuss [2007-05-11 00:03:36]
Note:
If you want to use % in sprintf, you have to "quote" it like %%.
Example:
echo sprintf("Green => %d%%'", 50);
Output:
Green => 50%
[#35] SWestrup [2006-11-09 11:46:34]
In response to Anonymous, who claimed that:
printf("[%s]\n", str_pad('Hello', 20));
and
printf("[%-20s]\n", 'Hello');
are the same thing: you've missed the point.
They're only the same when the amount of padding is a known constant. When its a variable (or an expression), its often much more convenient to be able to write:
printf("[%-*s]\n", 3*$n+2, "Hello");
than what you have to go through now, which is either:
$t = 3*$n+2;
printf("[%-{$t}s]\n","Hello");
or
printf("[%s]\n", str_pad('Hello', 3*$n+2));
[#36] bknakkerNO at SPAMgmail dot com [2006-08-10 14:54:20]
Note that in PHP5 (.1.4 for me) sprintf will not use the __toString function of an object.
<?php
class pr{
private $l;
public function __construct($l)
{
$this->l=$l;
}
public function __toString()
{
return $this->l;
}
}
echo new pr('This works!!'); //This will display 'This works!!'
echo sprintf(new pr('This doesnt')); // will display 'Object'
?>
Be careful with that!
[#37] tim dot brouckaert dot NOSPAM at gmail dot com [2005-10-12 05:35:33]
If you want to center align some text using the printf or sprintf functions, you can just use the following:
function center_text($word){
$tot_width = 30;
$symbol = "-";
$middle = round($tot_width/2);
$length_word = strlen($word);
$middle_word = round($length_word / 2);
$last_position = $middle + $middle_word;
$number_of_spaces = $middle - $middle_word;
$result = sprintf("%'{$symbol}{$last_position}s", $word);
for ($i = 0; $i < $number_of_spaces; $i++){
$result .= "$symbol";
}
return $result;
}
$string = "This is some text";
print center_text($string);
off course you can modify the function to use more arguments.
[#38] webmaster at cafe-clope dot net [2005-08-14 21:47:58]
trying to fix the multibyte non-compliance of sprintf, I came to that :
<?php
function mb_sprintf($format) {
$argv = func_get_args() ;
array_shift($argv) ;
return mb_vsprintf($format, $argv) ;
}
function mb_vsprintf($format, $argv) {
$newargv = array() ;
preg_match_all("`\%('.+|[0 ]|)([1-9][0-9]*|)s`U", $format, $results, PREG_SET_ORDER) ;
foreach($results as $result) {
list($string_format, $filler, $size) = $result ;
if(strlen($filler)>1)
$filler = substr($filler, 1) ;
while(!is_string($arg = array_shift($argv)))
$newargv[] = $arg ;
$pos = strpos($format, $string_format) ;
$format = substr($format, 0, $pos)
. ($size ? str_repeat($filler, $size-strlen($arg)) : '')
. str_replace('%', '%%', $arg)
. substr($format, $pos+strlen($string_format))
;
}
return vsprintf($format, $newargv) ;
}
?>
handle with care :
1. that function was designed mostly for utf-8. i guess it won't work with any static mb encoding.
2. my configuration sets the mbstring.func_overload configuration directive to 7, so you may wish to replace substr, strlen, etc. with mb_* equivalents.
3. since preg_* doesn't complies with mb strings, I used a '.+' in the regexp to symbolize an escaped filler character. That means, %'xy5s pattern will match, unfortunately. It is recomended to remove the '+', unless you are intending to use an mb char as filler.
4. the filler fills at left, and only at left.
5. I couldn't succeed with a preg_replace thing : the problem was to use the differents lengths of the string arguements in the same replacement, string or callback. That's why the code is much longuer than I expected.
6. The pattern wil not match any %1\$s thing... just was too complicated for me.
7. Although it has been tested, and works fine within the limits above, this is much more a draft than a end-user function. I would enjoy any improvment.
The test code below shows possibilities, and explains the problem that occures with an mb string argument in sprintf.
<?php
header("content-type:text/plain; charset=UTF-8") ;
$mb_string = "x?x?x" ;
echo sprintf("%010s", $mb_string), " [octet-size: ", str_sizeof($mb_string) , " ; count: ", strlen(sprintf("%010s", $mb_string)), " characters]\n" ;
echo mb_sprintf("%010s", $mb_string), " [octet-size: ", str_sizeof($mb_string) , " ; count: ", strlen(mb_sprintf("%010s", $mb_string)), " characters]\n" ;
echo "\n" ;
echo mb_sprintf("%''10s\n%'010s\n%'?10s\n%10d\n%'x10s\n%010s\n% 10s\n%010s\n%'1s\n", "zero", "one", "two", 3, "four", "??ve", "%s%i%x", "??ve?", "eight") ;
?>
[#39] david at rayninfo dot co dot uk [2005-06-16 23:33:20]
Using sprintf to force leading leading zeros
foreach (range(1, 10) as $v) {echo "<br>tag_".sprintf("%02d",$v);}
displays
tag_01
tag_02
tag_03
.. etc
[#40] ian dot w dot davis at gmail dot com [2005-05-30 07:03:43]
Just to elaborate on downright's point about different meanings for %f, it appears the behavior changed significantly as of 4.3.7, rather than just being different on different platforms. Previously, the width specifier gave the number of characters allowed BEFORE the decimal. Now, the width specifier gives the TOTAL number of characters. (This is in line with the semantics of printf() in other languages.) See bugs #28633 and #29286 for more details.
[#41] Pacogliss [2005-05-02 00:08:39]
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 ;-).
[#42] christian at wenz dot org [2005-04-18 00:20:44]
@ henke dot andersson at comhem dot se: Use vprintf()/vsprintf() for that.
[#43] henke dot andersson at comhem dot se [2005-04-15 08:07:42]
Mind that it doesn't allow you to use a array as multiple arguments like this:
<?php
printf('%s %s',array('a','b')) ?>
[#44] jrpozo at conclase dot net [2005-01-21 07:13:19]
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.
[#45] timo at frenay dot net [2005-01-10 10:58:10]
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));
?>
[#46] Gkeeper80 [2004-08-11 15:58:20]
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.
[#47] php at sharpdreams dot com [2004-05-08 14:13:21]
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" );
// Wont work:
// Sprintf will complain about not enough arguments.
$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" );
// Will work: note the %3\$s
?>
[#48] kekec at kukac dot hu [2004-03-29 09:16:40]
A really working one:
<?php
function cutzero($value) {
return preg_replace("/(\.?)0+$/", "", $value);
}
?>
[#49] info at nospam dot webtip dot dk [2003-02-18 05:06:18]
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
[#50] no dot email dot address at example dot com [2002-09-16 06:29:36]
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.
[#51] abiltcliffe at bigfoot.com [2002-09-10 11:01:26]
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).
[#52] Andrew dot Wright at spamsux dot atnf dot csiro dot au [2002-07-03 02:22:14]
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);
[#53] cv at corbach dot de [2002-02-10 07:36:56]
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)));
[#54] tjchamberlain.hotmail@com [2001-03-25 23:16:32]
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.
[#55] prolixmp3 at navigators dot lv [2001-03-23 10:55:49]
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)
[#56] voudras at nospam dot swiftslayer dot org [2000-11-17 06:58:21]
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