将字符串转换为整数,在其前面加一个零


Convert a string to integer, adding one with zero before it?

我有一些字符串,其中包含表示一个月的数据。例如,"00"是一月,"01"是二月,"02"是三月,依此类推。我如何让字符串像这样表示"01"是一月,"02"是二月等等,这是一种更简单的方法。我找不到任何一个PHP函数能起到这个作用。

/*如果小于一位,请键入cast month to 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; 
}

提前感谢

除了使用str_pad,您还可以使用sprintf:

$month = "00";
$month = (int) $month;
$month += 1;
$month = sprintf("%02s", $month);

或者,更短:

$month = sprintf("%02s", $month + 1);

您的方法几乎是最简单的选择,但您不需要检查月份的大小,str_pad可以帮您完成。

$month = "00"; // represents January
$month = (int) $month;
$month += 1;
$month = str_pad($month, 2, "0", STR_PAD_LEFT);

怎么样:

$month = "00"; // represents January
// just increment the string value
// comment out the to display the different months
$month++; 
$month++;
$month++;
$month++;
$month++;
$month++;
$month++;
$month++;
$month++;
$month++;
$month++;
$month++;
// Month = 13 when un-commenting, but should return 01
// $month++;

$month = ($month > 12) ? "01": str_pad($month, 2, "0", STR_PAD_LEFT);
echo "Month: {$month}'n";

不确定这是否是你的意思:

switch($monthString)
{
case "January": $monthInt = "00";
break;
case "Febuary": $monthInt = "01";
break;
case "March": $monthInt = "02";
break;
case "April": $monthInt = "03";
break;
...
}