PHP sprintf() 函數的應用(定義和用法)_PHP教程

來源:互聯網
上載者:User

文法

sprintf(format,arg1,arg2,arg++)
參數 描述
format 必需。轉換格式。
arg1 必需。規定插到 format 字串中第一個 % 符號處的參數。
arg2 可選。規定插到 format 字串中第二個 % 符號處的參數。
arg++ 可選。規定插到 format 字串中第三、四等等 % 符號處的參數。

說明

參數 format 是轉換的格式,以百分比符號 ("%") 開始到轉換字元結束。下面的可能的 format 值:
%% - 返回百分比符號
%b - 位元
%c - 依照 ASCII 值的字元
%d - 帶符號十進位數
%e - 可續計數法(比如 1.5e+3)
%u - 無符號十進位數
%f - 浮點數(local settings aware)
%F - 浮點數(not local settings aware)
%o - 八位元
%s - 字串
%x - 十六進位數(小寫字母)
%X - 十六進位數(大寫字母)
arg1, arg2, ++ 等參數將插入到主字串中的百分比符號 (%) 符號處。該函數是逐步執行的。在第一個 % 符號中,插入 arg1,在第二個 % 符號處,插入 arg2,依此類推

提示和注釋
注釋:如果 % 符號多於 arg 參數,則您必須使用預留位置。預留位置插到 % 符號後面,由數字和 "\$" 組成。請參見例子 3。

例子
例子 1
複製代碼 代碼如下:
?
$str = "Hello";
$number = 123;
$txt = sprintf("%s world. Day number %u",$str,$number);
echo $txt;
?>

輸出:

Hello world. Day number 123

例子 2
複製代碼 代碼如下:
$number = 123;
$txt = sprintf("%f",$number);
echo $txt;
?>
 

輸出:

123.000000

例子 3
複製代碼 代碼如下:
$number = 123;
$txt = sprintf("With 2 decimals: %1\$.2f
With no decimals: %1\$u",$number);
echo $txt;
?>

輸出:
複製代碼 代碼如下:
With 2 decimals: 123.00
With no decimals: 123

例子4
複製代碼 代碼如下:
$ctype_primary = strtolower('application');
$ctype_secondary = strtolower('pdf');
$mimetype = sprintf('%s/%s', $ctype_primary, $ctype_secondary);
echo $mimetype;
?>

輸出:
複製代碼 代碼如下:
application/pdf

http://www.bkjia.com/PHPjc/325510.htmlwww.bkjia.comtruehttp://www.bkjia.com/PHPjc/325510.htmlTechArticle文法 sprintf(format,arg1,arg2,arg++) 參數 描述 format 必需。轉換格式。 arg1 必需。規定插到 format 字串中第一個 % 符號處的參數。 arg2 可選。規...

  • 聯繫我們

    該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

    如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

    A Free Trial That Lets You Build Big!

    Start building with 50+ products and up to 12 months usage for Elastic Compute Service

    • Sales Support

      1 on 1 presale consultation

    • After-Sales Support

      24/7 Technical Support 6 Free Tickets per Quarter Faster Response

    • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.