PHP vfprintf()関数
例
「test.txt」という名前のテキストファイルにテキストを書き込みます。
<?php
$number = 9;
$str = "Beijing";
$file = fopen("test.txt","w");
echo vfprintf($file,"There are %u million bicycles in %s.",array($number,$str));
?>
上記のコードの出力は次のようになります。
40
次のテキストがファイル「test.txt」に書き込まれます。
There are 9 million bicycles in Beijing.
定義と使用法
vfprintf()関数は、フォーマットされた文字列を指定された出力ストリーム(例:ファイルまたはデータベース)に書き込みます。
fprintf()とは異なり、vfprintf()の引数は配列に配置されます。配列要素は、メイン文字列のパーセント(%)記号で挿入されます。この機能は「段階的に」機能します。最初の%記号で最初の配列要素が挿入され、2番目の%記号で2番目の配列要素が挿入されます。
注:引数よりも%記号が多い場合は、プレースホルダーを使用する必要があります。プレースホルダーは%記号の後に挿入され、引数番号と「\ $」で構成されます。例2を参照してください。
ヒント:関連する関数:fprintf()、 printf()、 sprintf()、vprintf()、 vsprintf()。
構文
vfprintf(stream,format,argarray)
パラメータ値
Parameter | Description |
---|---|
stream | Required. Specifies where to write/output the string |
format | Required. Specifies the string and how to format the variables in it. Possible format values:
Additional format values. These are placed between the % and the letter (example %.2f):
Note: If multiple additional format values are used, they must be in the same order as above. |
argarray | Required. An array with arguments to be inserted at the % signs in the format string |
技術的な詳細
戻り値: | 書き込まれた文字列の長さを返します |
---|---|
PHPバージョン: | 5歳以上 |
その他の例
例
ファイルにテキストを書き込みます。
<?php
$num1 = 123;
$num2 = 456;
$file = fopen("test.txt","w");
vfprintf($file,"%f%f",array($num1,$num2));
?>
次のテキストがファイル「test.txt」に書き込まれます。
123.000000456.000000
例
プレースホルダーの使用:
<?php
$number = 123;
$file = fopen("test.txt","w");
vfprintf($file,"With 2 decimals: %1\$.2f
\nWith no decimals: %1\$u",array($number));
?>
次のテキストがファイル「test.txt」に書き込まれます。
With 2 decimals: 123.00
With no decimals: 123
例
printf()を使用して、可能なすべてのフォーマット値を示します。
<?php
$num1 = 123456789;
$num2 = -123456789;
$char = 50; // The ASCII Character 50 is 2
// Note: The format value "%%" returns a percent sign
printf("%%b = %b <br>",$num1); // Binary number
printf("%%c = %c <br>",$char); // The ASCII Character
printf("%%d = %d <br>",$num1); // Signed decimal number
printf("%%d = %d <br>",$num2); // Signed decimal number
printf("%%e = %e <br>",$num1); // Scientific notation (lowercase)
printf("%%E = %E <br>",$num1); // Scientific notation (uppercase)
printf("%%u = %u <br>",$num1); // Unsigned decimal number (positive)
printf("%%u = %u <br>",$num2); // Unsigned decimal number (negative)
printf("%%f = %f <br>",$num1); // Floating-point number (local settings aware)
printf("%%F = %F <br>",$num1); // Floating-point number (not local settings aware)
printf("%%g = %g <br>",$num1); // Shorter of %e and %f
printf("%%G = %G <br>",$num1); // Shorter of %E and %f
printf("%%o = %o <br>",$num1); // Octal number
printf("%%s = %s <br>",$num1); // String
printf("%%x = %x <br>",$num1); // Hexadecimal number (lowercase)
printf("%%X = %X <br>",$num1); // Hexadecimal number (uppercase)
printf("%%+d = %+d <br>",$num1); // Sign specifier (positive)
printf("%%+d = %+d <br>",$num2); // Sign specifier (negative)
?>
❮PHP文字列リファレンス