PHP中printf()函数格式化使用详解

- 8 mins

格式组成说明

格式字符说明

格式字符用以指定输出项的数据类型和输出格式。

特殊说明

如果想输出字符”%”,则应该在“格式控制”字符串中用连续两个%表示,如:

printf("%f%%", 1.0/3); // 输出0.333333%。

例子

printf

说明 printf ( string $format [, mixed $args [, mixed $... ]] ) : int 例子:

printf("ni hao %s and %d\n", 'holle world', 123);  //ni hao holle world and 123

printf("ni hao %2\$s and %1\$s \n", 'holle world', 'holle world2');  //ni hao holle world2 and holle world

printf("%04d", 2);  //0002

sprintf

说明 sprintf ( string $format [, mixed $... ] ) : string

$num = 5;
$location = 'tree';

$format = 'There are %d monkeys in the %s';
echo sprintf($format, $num, $location);

// 指定顺序
$format = 'The %2$s contains %1$d monkeys';
echo sprintf($format, $num, $location);

echo PHP_EOL;

// 填充
echo sprintf("%'.9d\n", 123);
echo sprintf("%'*9d\n", 123);

echo sprintf("%04d", 123);

echo PHP_EOL;

$format = 'The %2$s contains %1$04d monkeys';
echo sprintf($format, $num, $location);

Result:

There are 5 monkeys in the treeThe tree contains 5 monkeys
......123
******123
0123
The tree contains 0005 monkeys
<?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'

vsprintf - 返回格式化字符串

说明 vsprintf ( string $format , array $args ) : string
作用与 sprintf() 函数类似,但是接收一个数组参数,而不是一系列可变数量的参数。 例子:

print vsprintf("%04d-%02d-%02d", explode('-', '1988-8-1')); // 1988-08-01

echo PHP_EOL;

$string = "
I like the state of %1\$s <br />
I picked: %2\$d as a number, <br />
I also picked %2\$d as a number again <br />
%3\$s<br /> ";

$returnText = vprintf(  $string, array('Oregon','7','I Love Oregon')  );

echo $returnText;

/* result
I like the state of Oregon <br />
I picked: 7 as a number, <br />
I also picked 7 as a number again <br />
I Love Oregon<br />
*/

vsprintf扩展功能函数vnsprintf

function vnsprintf( $format, array $data)
{
    preg_match_all( '/ (?<!%) % ( (?: [[:alpha:]_-][[:alnum:]_-]* | ([-+])? [0-9]+ (?(2) (?:\.[0-9]+)? | \.[0-9]+ ) ) ) \$ [-+]? \'? .? -? [0-9]* (\.[0-9]+)? \w/x', $format, $match, PREG_SET_ORDER | PREG_OFFSET_CAPTURE);
    $offset = 0;
    $keys = array_keys($data);
    foreach ( $match as &$value )
    {
        if ( ( $key = array_search( $value[1][0], $keys) ) !== FALSE || ( is_numeric( $value[1][0]) && ( $key = array_search( (int)$value[1][0], $keys) ) !== FALSE ) ) {
            $len = strlen( $value[1][0]);
            $format = substr_replace( $format, 1 + $key, $offset + $value[1][1], $len);
            $offset -= $len - strlen( $key);
        }
    }
    return vsprintf( $format, $data);
}

例子:(来自PHP手册)

$examples = array(
    2.8=>'positiveFloat',    // key = 2 , 1st value
    -3=>'negativeInteger',    // key = -3 , 2nd value
    'my_name'=>'someString'    // key = my_name , 3rd value
);

echo vsprintf( "%%my_name\$s = '%my_name\$s'\n", $examples);    // [unsupported]
echo vnsprintf( "%%my_name\$s = '%my_name\$s'\n", $examples);    // output : "someString"

echo vsprintf( "%%2.5\$s = '%2.5\$s'\n", $examples);        // [unsupported]
echo vnsprintf( "%%2.5\$s = '%2.5\$s'\n", $examples);        // output : "positiveFloat"

echo vsprintf( "%%+2.5\$s = '%+2.5\$s'\n", $examples);        // [unsupported]
echo vnsprintf( "%%+2.5\$s = '%+2.5\$s'\n", $examples);        // output : "positiveFloat"

echo vsprintf( "%%-3.2\$s = '%-3.2\$s'\n", $examples);        // [unsupported]
echo vnsprintf( "%%-3.2\$s = '%-3.2\$s'\n", $examples);        // output : "negativeInteger"

echo vsprintf( "%%2\$s = '%2\$s'\n", $examples);            // output : "negativeInteger"
echo vnsprintf( "%%2\$s = '%2\$s'\n", $examples);            // output : [= vsprintf]

echo vsprintf( "%%+2\$s = '%+2\$s'\n", $examples);        // [unsupported]
echo vnsprintf( "%%+2\$s = '%+2\$s'\n", $examples);        // output : "positiveFloat"

echo vsprintf( "%%-3\$s = '%-3\$s'\n", $examples);        // [unsupported]
echo vnsprintf( "%%-3\$s = '%-3\$s'\n", $examples);        // output : "negativeInteger"

PS: 以上大部分来自PHP手册上的例子,算是对一些用法的总结。

由于本人水平有限,文章在表述和代码方面如有不妥之处,欢迎批评指正。

rss facebook twitter github gitlab youtube mail spotify lastfm instagram linkedin google google-plus pinterest medium vimeo stackoverflow reddit quora quora