我在php中有一个动态生成的变量,名为$ date,看起来像....
12-02-1972
23-03-1985
18-12-1992
6-04-2001
我想把这个$ date字符串分成单独的组件,以便我最终得到....
$day
$month
$year
这样做的最佳方法是什么,某种正则表达式用于将数字与破折号分开?或者有更好的方法吗?
答案 0 :(得分:6)
尝试:
list($day, $month, $year) = explode('-', '12-02-1972');
答案 1 :(得分:2)
$date = new DateTime('2000-01-01');
echo $date->format('Y-m-d');
年份Y , m 持续数月, d 持续数天
所以你的例子:
$year = $date->format('Y');
$month = $date->format('m');
$day = $date->format('d');
格式化您需要的方式
答案 2 :(得分:2)
sscanf('12-02-1972', "%d-%d-%d", $day, $month, $year);
# now you have variables $day, $month and $year filled with values
P.S。返回值是整数,而不是字符串
答案 3 :(得分:2)
使用PHP函数explode();
$date = "12-02-1972";
$date = explode('-', $date);
$date[0]; // this is your day
$date[1]; // this is your month
$date[2]; // this is your year
答案 4 :(得分:1)
$day = date($date, 'd');
$month = date($date, 'm');
$year = date($date, 'Y');