sprintf

(PHP 4, PHP 5, PHP 7, PHP 8)

sprintfフォーマットされた文字列を返す

説明

function sprintf(string $format, mixed ...$values): string

フォーマット文字列 format に基づき生成された文字列を返します。

パラメータ

format

0個以上のディレクティブで構成されるフォーマット文字列: 変換結果に直接コピーされる通常文字列 (% は除きます) と、変換仕様。 これらのいずれも、自分が持つパラメータを取得します。

変換の仕様は、以下のプロトタイプに従います: %[argnum$][flags][width][.precision]specifier.

Argnum

何番目の引数を変換の対象にするかを指定するために、 数値の後にドル記号 $ を続けます。

Flags

フラグ 説明
- 与えられたフィールドの幅を左寄せにします。 右寄せがデフォルトです。
+ 正の数値の前に付ける + 符号です; デフォルトは、負の数にだけマイナスの符号が数値の前に付きます。
(space) スペースに変換される詰め物です。 これがデフォルトです。
0 数値の左側を0埋めします。 s 指定子を使うと、 右側にも0埋めできます。
'(char) 指定された (char) で埋めます。

Width

(最小で)何文字がこの変換結果に含まれるかを数値で指定するか、 * を指定します。 * を指定した場合、 指定子によってフォーマットされる値の前に、 幅を追加の数値として指定します。

Precision

ピリオド . の後に数値を続けるか、 * を続けますが、 その意味は指定子に依存します:

  • e, E, fF 指定子の場合: 小数点の後に表示する桁数 (デフォルトでは、この値は6です)

  • g, G, h, H 指定子の場合: 表示する最大の有効桁数

  • s 指定子の場合: 文字列を切り捨てる時点、つまり、文字列の最大の長さを設定します。

注意:

明示的に精度を指定せず、ピリオドを指定した場合、精度は0として扱われます。 * を使った場合、 精度は指定子によってフォーマットされる値の前に、 追加の数値として指定します。

指定子の一覧
指定子 説明
% 文字通り、パーセント文字です。 引数は不要です。
b 引数は整数として扱われ、2進数値として表現されます。
c 引数は整数として扱われ、ASCII文字として表現されます。
d 引数は整数として扱われ、(符号付き)10進数値として表現されます。
e 引数は科学的記法で表現された値(e.g. 1.2e+2)として扱われます。
E e 指定子に似ていますが、 大文字を使います(e.g. 1.2E+2)
f 引数は小数として扱われ、浮動小数点数値として表現されます(ロケールを考慮します)。
F 引数は小数として扱われ、浮動小数点数値として表現されます(ロケールを考慮しません)。
g 汎用フォーマット P を、精度が 0 でなければその精度、 精度が省略された場合は 6、 精度に 0 を指定した場合は 1 とします。 そして、E 指定子で変換した場合の指数を X とします: P > X ≥ −4 の場合、f 指定子による変換となり、精度は、P − (X + 1) になります。 そうでない場合、e 指定子による変換となり、 精度は、P − 1 になります。
G g 指定子に似ていますが、 Ef を使います。
h g 指定子に似ていますが、 F を使います。 PHP 8.0.0 以降で利用可能です。
H g 指定子に似ていますが、 EF を使います。 PHP 8.0.0 以降で利用可能です。
o 引数は整数として扱われ、8進数値として表現されます。
s 引数は文字列として扱われ、文字列として表現されます。
u 引数は整数として扱われ、符号なし10進数値として表現されます。
x 引数は整数として扱われ、16進数値(小文字)として表現されます。
X 引数は整数として扱われ、16進数値(大文字)として表現されます。

警告

c 指定子はパディングと幅を無視します

警告

文字列と width 指定子を、1文字の表現に1バイト以上必要な文字セットと一緒に使おうとすると、 期待しない結果になるかもしれません。

値は、指定子の型に合うように強制されます:

型のハンドリング
指定子
string s
int d, u, c, o, x, X, b
float e, E, f, F, g, G, h, H

values

戻り値

フォーマット文字列 format に基づき生成された文字列を返します。

エラー / 例外

 PHP 8.0.0 以降では、 引数の数が0の場合に ValueError がスローされます。 これより前のバージョンでは、代わりに E_WARNING を発生させていました。

PHP 8.0.0 以降では、 [width] の値が0より小さかったり、 PHP_INT_MAX より大きい場合に、 ValueError がスローされます。 これより前のバージョンでは、代わりに E_WARNING を発生させていました。

PHP 8.0.0 以降では、 [precision] の値が0より小さかったり、 PHP_INT_MAX より大きい場合に、 ValueError がスローされます。 これより前のバージョンでは、代わりに E_WARNING を発生させていました。

PHP 8.0.0 以降では、 引数が必要な数より少なかった場合、 ArgumentCountError がスローされます。 これより前のバージョンでは、代わりに false を返し、E_WARNING を発生させていました。

変更履歴

バージョン 説明
8.0.0 この関数は、失敗時に false を返さなくなりました。
8.0.0 引数の数が0だった場合、 ValueError がスローされるようになりました。 これより前のバージョンでは、代わりに E_WARNING を発生させていました。
8.0.0 [width] の値が0より小さかったり、 PHP_INT_MAX より大きい場合に、 ValueError をスローするようになりました。 これより前のバージョンでは、代わりに E_WARNING を発生させていました。
8.0.0 [precision] の値が0より小さかったり、 PHP_INT_MAX より大きい場合に、 ValueError をスローするようになりました。 これより前のバージョンでは、代わりに E_WARNING を発生させていました。
8.0.0 引数が必要な数より少なかった場合、 ArgumentCountError がスローされるようになりました。 これより前のバージョンでは、代わりに E_WARNING を発生させていました。

例1 引数の交換

フォーマット文字列における引数の 番号付け/交換 をサポートしています。

<?php
$num = 5;
$location = 'tree';

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

上の例の出力は以下となります。

There are 5 monkeys in the tree

ここで、フォーマット文字列が別のファイルにある場合を考えてみましょう。 これは、出力を国際化したりする場合に行われる可能性があります。 たとえばフォーマット文字列が次のように書き換えられたとすると、

例2 間違った引数の順番

フォーマット文字列における引数の 番号付け/交換 をサポートしています。

<?php
$num = 5;
$location = 'tree';

$format = 'The %s contains %d monkeys';
echo sprintf($format, $num, $location);
?>

ここで、問題が発生します。フォーマット文字列における置換指示子の順番は、 コードにおける引数の順番と一致していません。 コードはそのままにして、各置換指示子がどの引数を参照するのかを フォーマット文字列の側で指定するのが望ましいでしょう。 フォーマット文字列を次のように書き換えてみましょう。

例3 順序付きの置換指示子

<?php
$num = 5;
$location = 'tree';

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

こうすることによるもうひとつの利点は、 同じ置換指示子を複数回使用する際にコードに引数を追加せずにすむことです。

例4 置換指示子を繰り返し使う

<?php
$num = 5;
$location = 'tree';

$format = 'The %2$s contains %1$d monkeys.
           That\'s a nice %2$s full of %1$d monkeys.';
echo sprintf($format, $num, $location);
?>

引数の交換を使うときには、 位置指定子 n$ をパーセント記号 (%) の直後に置かなければならず、 間に他の指定を入れてはいけません。次に例を示します。

例5 パディング文字を指定する

<?php
echo sprintf("%'.9d\n", 123);
echo sprintf("%'.09d\n", 123);
?>

上の例の出力は以下となります。

......123
000000123

例6 他の指定子と一緒に位置指定子を使う

<?php
$num = 5;
$location = 'tree';

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

上の例の出力は以下となります。

The tree contains 0005 monkeys

例7 sprintf(): 整数を0埋めする

<?php
$year = 2005;
$month = 5;
$day = 6;

$isodate = sprintf("%04d-%02d-%02d", $year, $month, $day);
echo $isodate, PHP_EOL;
?>

例8 sprintf(): 通貨をフォーマットする

<?php
$money1 = 68.75;
$money2 = 54.35;
$money = $money1 + $money2;
echo $money, PHP_EOL;

$formatted = sprintf("%01.2f", $money);
echo $formatted, PHP_EOL;
?>

上の例の出力は以下となります。

123.1
123.10

例9 sprintf(): 科学的記法

<?php
$number = 362525200;

echo sprintf("%.3e", $number), PHP_EOL;
?>

上の例の出力は以下となります。

3.625e+8

参考

  • printf() - フォーマット済みの文字列を出力する
  • fprintf() - フォーマットされた文字列をストリームに書き込む
  • vprintf() - フォーマットされた文字列を出力する
  • vsprintf() - フォーマットされた文字列を返す
  • vfprintf() - フォーマットされた文字列をストリームに書き込む
  • sscanf() - フォーマット文字列に基づき入力を処理する
  • fscanf() - フォーマットに基づきファイルからの入力を処理する
  • number_format() - 数字を千の位毎にグループ化してフォーマットする
  • date() - Unixタイムスタンプを書式化する

add a note

User Contributed Notes 34 notes

up
109
remy dot damour at -please-no-spam-laposte dot net
17 years ago
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%'
?>
up
74
Alex R. Gibbs
13 years ago
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  |
up
7
iannacone
2 years ago
it is also worth to notice that Argnum starts from 1 and NOT 0
up
5
Anonymous
4 years ago
If the format string is enclosed in double-quotes (""), you need to escape the dollar sign after argnum with a backslash character (\), like this %1\$s, so that the PHP doesn't try to interpret them as variable. Using a backslash like this is called an escape sequence.

<?php
// Sample string
$number = 499;
$format = "The number without decimal points: %1\$d, and the number with two decimal points: %1\$.2f";

// Formatting and print the string
printf($format, $number);
?>
up
24
kontakt at myseosolution dot de
11 years ago
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.
up
17
timo dot frenay at gmail dot com
15 years ago
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.
up
17
viktor at textalk dot com
17 years ago
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')) {
  /**
   * Works with all encodings in format and arguments.
   * Supported: Sign, padding, alignment, width and precision.
   * Not supported: Argument swapping.
   */
  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);
  }
}
?>
up
11
krzysiek dot 333 at gmail dot com - zryty dot hekko dot pl
15 years ago
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]);
}
?>
up
12
nate at frickenate dot com
16 years ago
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

/**
 * version of sprintf for cases where named arguments are desired (php syntax)
 *
 * with sprintf: sprintf('second: %2$s ; first: %1$s', '1st', '2nd');
 *
 * with sprintfn: sprintfn('second: %second$s ; first: %first$s', array(
 *  'first' => '1st',
 *  'second'=> '2nd'
 * ));
 *
 * @param string $format sprintf format string, with any number of named arguments
 * @param array $args array of [ 'arg_name' => 'arg value', ... ] replacements to be made
 * @return string|false result of sprintf call, or bool false on error
 */
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));
}

/**
 * version of sprintf for cases where named arguments are desired (python syntax)
 *
 * with sprintf: sprintf('second: %2$s ; first: %1$s', '1st', '2nd');
 *
 * with sprintfn: sprintfn('second: %(second)s ; first: %(first)s', array(
 *  'first' => '1st',
 *  'second'=> '2nd'
 * ));
 *
 * @param string $format sprintf format string, with any number of named arguments
 * @param array $args array of [ 'arg_name' => 'arg value', ... ] replacements to be made
 * @return string|false result of sprintf call, or bool false on error
 */
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;