PHP sprintf()鍑芥暟鐨勮В鍐冲姙娉


杩欑瘒鏂囩珷涓昏涓哄ぇ瀹惰缁嗕粙缁嶄簡PHP sprintf()鍑芥暟鐨勭畝鍗曠ず渚嬶紝鍏锋湁涓瀹氱殑鍙傝冧环鍊硷紝鍙互鐢ㄦ潵鍙傝冧竴涓嬨

瀵规鎰熷叴瓒g殑鏈嬪弸锛岀湅鐪媔dc绗旇鍋氱殑鎶鏈瑪璁帮紒

浠g爜濡備笅:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
<code>
<?php
//sprintf()鍑芥暟锛岃繑鍥炲间负鏍煎紡鍖栧悗鐨勫瓧绗︿覆
string sprintf ( string $format [, mixed $args [, mixed $... ]] )
 
$y = 11;
$m = 3;
$d = 9;
$date = sprinf(鈥%04d-%02d-%02d', $y, $m ,$d);
echo $date; //0011-0
//printf()鍑芥暟锛岃繑鍥炲间负鏍煎紡鍖栧悗鐨勫瓧绗︿覆闀垮害
int printf ( string $format [, mixed $args [, mixed $... ]] )
$num = 3.14;
printf(鈥滃瓧绗﹀~鍏 %'#6.2s鈥, $num); //##3.14
//瀛楃闀垮害涓6锛屾湁鏁扮偣鍚2锛屼笉瓒6浣嶏紝#濉厖
</code>
sprintf() 涓 printf() 鍖哄埆璇硶鏍煎紡涓鏍凤紝鍙槸杩斿洖鍊间笉鍚屽畾涔夊拰鐢ㄦ硶sprintf() 鍑芥暟鎶婃牸寮忓寲鐨勫瓧绗︿覆鍐欏啓鍏ヤ竴涓彉閲忎腑銆傝娉晄printf(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锛屼緷姝ょ被鎺ㄣ備緥瀛愪緥瀛 1

浠g爜濡備笅:

1
2
3
4
5
6
7
8
<code>
<?php
$str = "Hello";
$number = 123;
$txt = sprintf("%s world. Day number %u",$str,$number);
echo $txt;
?>
</code>
杈撳嚭锛欻ello world. Day number 123渚嬪瓙 2

浠g爜濡備笅:

1
2
3
4
5
6
7
<code>
<?php
$number = 123;
$txt = sprintf("%f",$number);
echo $txt;
?>
</code>
杈撳嚭锛123.000000渚嬪瓙 3

浠g爜濡備笅:

1
2
3
4
5
6
7
<code>
<?php
$number = 123;
$txt = sprintf("With 2 decimals: %1\$.2f<br />With no decimals: %1\$u",$number);
echo $txt;
?>
</code>
杈撳嚭锛歐ith 2 decimals: 123.00With no decimals: 123

浠ヤ笂灏辨槸PHP sprintf()鍑芥暟鐨勮В鍐冲姙娉曠殑璇︾粏鍐呭锛屾洿澶氫俊鎭鍏虫敞OD浜戝叾瀹冪浉鍏虫枃绔狅紒



鏈枃URL锛http://www.odweb.cn/news_show.html?id=131