true checkMonth("Mar") => true checkMonth(02) => true ch-6ren">
gpt4 book ai didi

php - 如何检查给定的字符串是否为有效月份?

转载 作者:搜寻专家 更新时间:2023-10-31 20:38:41 24 4
gpt4 key购买 nike

我正在制作一个函数来检查月份是否有效。例如。

checkMonth("Feb") => true

checkMonth("Mar") => true

checkMonth(02) => true

checkMonth(2) => true

但是

checkMonth("X") => false

checkMonth("XYZ") => false

数字形式 2 或 02 没有问题。但是,如果我传递像“X”或“XYZ”这样的参数,它就不起作用并返回 true。

我在努力

echo date('n', strtotime("XYZ"));

返回 true 是因为 date('n', strtotime("XYZ")) 的值为 3,这是一个有效的月份。

我也试过

$mon=date_format(date_create("XYZ"),"n");

但它有同样的效果。

最佳答案

$month = 'XYZ';
$x = DateTime::createFromFormat('M', $month);
if (!$x) {
die($month . ' is not a valid month');
}
echo $month, 'is month number ', $x->format('n'), PHP_EOL;

(仅适用于几个月的英文名称)

关于php - 如何检查给定的字符串是否为有效月份?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/29027135/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com