2013-09-30 15 views
-1

我在PHP動態生成的變量稱爲它看起來像$日期....轉換合併日期變量爲單獨的項目

12-02-1972 
23-03-1985 
18-12-1992 
6-04-2001 

我想借此$日期字符串,並將其分割成獨立的公司組件,這樣我結束了例如....

$day 
$month 
$year 

什麼是這樣做的最佳方式,某種正則表達式的,從短線分離出位?或者,還有更好的方法?

回答

1

使用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 
5

嘗試:

list($day, $month, $year) = explode('-', '12-02-1972'); 
+0

+1:這個答案比接受的一種方式更好。 –

1

使用DateTimeformat

$date = new DateTime('2000-01-01'); 
echo $date->format('Y-m-d'); 

Ÿ爲一年,幾個月,d

所以,你的例子:

$year = $date->format('Y'); 
$month = $date->format('m'); 
$day = $date->format('d'); 

格式你曾經需要它

1
sscanf('12-02-1972', "%d-%d-%d", $day, $month, $year); 
# now you have variables $day, $month and $year filled with values 

附:返回值是整數,不是字符串

1
$day = date($date, 'd'); 
$month = date($date, 'm'); 
$year = date($date, 'Y'); 
相關問題