PHP格式化字符串函數 sprintf()


定義和用法

sprintf() 函數把格式化的字符串寫入一個變量中。

語法

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。

提示: 相關函數: fprintf()、 printf()、 vfprintf()、 vprintf() 以及 vsprintf()

例子

例子 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

 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM