我有代表一個月的數據的字符串。例如,「00」是1月,「01」是2月,「02」是3月等等。 如何讓字符串表示爲「01」是1月,「02」是2月等等,這是一種更簡單的方法。我找不到任何可以做到的技巧。將字符串轉換爲整數,在其之前添加一個零?
/* 型投每月爲int,如果低於一個數字加一個零,並轉換爲字符串 ELSEIF超過9(2位)轉換爲字符串提前 */
$month = "00"; // represents January
$month = (int) $month;
$month += 1;
if ($month <= 9){
$month = str_pad($month, 2, "0", STR_PAD_LEFT);
}
elseif ($month > 9){
$month = (string) $month;
}
感謝
我真的很喜歡這個答案,瞭解有關該功能的PHP文件,但無法理解它100%時,第一個參數是對我來說有點混亂,幸虧雖然:) – Vartox
我在不太好PHP但'%'應該啓動格式字符串, –
我不太擅長PHP。從右到左應該是:這是一個寬度爲2個字符的字符串;如果只有一個字符(即<10),則填充/填充「0」。 '%'開始格式字符串。我認爲格式類似於C函數sprintf:[link](http://www.tutorialspoint.com/c_standard_library/c_function_sprintf.htm)希望有幫助。 –