四、printf函數 printf函數返回一個格式化后的字符串。 語法:printf(format,arg1,arg2,arg++) 參數 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, arg++ 等參數將插入到主字符串中的百分號 (%) 符號處。該函數是逐步執行的,在第一個 % 符號中,插入 arg1,在第二個 % 符號處,插入 arg2,依此類推。如果 % 符號多于 arg 參數,則您必須使用占位符。占位符被插入 % 符號之后,由數字和 “/$” 組成。可使用數字指定顯示的參數,詳情請看例子。 例子: 復制代碼 代碼如下: ?php printf("My name is %s %s。","55nav", "com"); // My name is 55nav com。 printf("My name is %1/$s %1/$s","55nav", "com"); // 在s前添加1/$或2/$.....表示后面的參數顯示的位置,此行輸出 My name is 55nav 55nav因為只顯示第一個參數兩次。 printf("My name is %2/$s %1/$s","55nav", "com"); // My name is com 55nav ?
五、sprintf函數 此函數使用方法和printf一樣,唯一不同的就是該函數把格式化的字符串寫寫入一個變量中,而不是輸出來。 例子: 復制代碼 代碼如下: ?php sprintf("My name is %1/$s %1/$s","55nav", "com"); //你會發現沒有任何東西輸出的。 $out = sprintf("My name is %1/$s %2/$s","55nav", "com"); echo $out; //輸出 My name is 55nav com ?