[php]sprintf() 函數把格式化的字符串寫寫入一個變量中。
參數 format 是轉換的格式,以百分比符號 ("%") 開始到轉換字符結束。下面的可能的 format 值:
%% - 返回百分比符號
%b - 二進制數
%c - 依照 ASCII 值的字符
%d - 帶符號十進制數
%e - 可續計數法(比如 1.5e+3)
%u - 無符號十進制數
%f - 浮點數(local settings aware)
%F - 浮點數(not local settings aware)
%o - 八進制數
%s - 字符串
%x - 十六進制數(小寫字母)
%X - 十六進制數(大寫字母)
官方範例
<?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
?>
例子 1
<?php
$str = "Hello";
$number = 123;
$txt = sprintf("%s world. Day number %u",$str,$number);
echo $txt;
?>
輸出:
Hello world. Day number 123
例子 2
<?php
$number = 123;
$txt = sprintf("%f",$number);
echo $txt;
?>
輸出:
123.000000
例子 3
<?php
$number = 123;
$txt = sprintf("With 2 decimals: %1\$.2f<br />With no decimals: %1\$u",$number);
echo $txt;
?>
輸出:
With 2 decimals: 123.00
With no decimals: 123
- 6月 02 週四 201110:10
[php]sprintf() 函數把格式化的字符串寫寫入一個變量中。
文章標籤
全站熱搜
