2014-01-13 172 views
-1

您好,我希望從給定的字符串中獲取「2014年1月8日」的日期。從字符串中提取日期+ PHP

Wednesday, 8 January 2014 at 17:40 

如果您可以使用preg_replace將會很好嗎?

+2

你至今嘗試過什麼? –

+0

我還沒有想法與preg_replace,但現在usig它$ res = date('M d,Y',strtotime(trim(substr($ res,10,15)))); – alex

+0

我懷疑你需要使用preg_replace,因爲它格式良好,不應該有任何問題將它轉換爲帶'strtotime'的日期,然後使用'date'來合成它'$ date = date(「d FY「,strtotime(」2014年1月8日星期三17:40「));' – Breezer

回答

3

PHP strtotime爲 「在」 理解這個詞壞的,所以這段代碼應該工作而不是返回1970年:

$date = date("d F Y", strtotime(str_replace('at ','',"Wednesday, 8 January 2014 at 17:40"))); 
echo $date; 

你可以根據需要更改格式;只需更改字母d F Y並返回不同值的字母列表可以找到in the manual

1

與爆炸剛纔提出的解決方案()函數:

$str = "Wednesday, 8 January 2014 at 17:40"; 
$ex1 = explode(", ", $str); 
$ex2 = explode(" at", $ex1[1]); 
$value = $ex2[0]; 
echo $value; 
0

嘗試正則表達式模式是這樣的:

$str = 'Wednesday, 8 January 2014 at 17:40'; 
$date = preg_replace('/\w+,\s([a-zA-Z0-9\s]+)\sat\s([0-9:]+)/i', '$1', $str); 
echo $date; 
1

DateTime類讓你的生活更簡單!

<?php 
$date = DateTime::createFromFormat('l, j F Y \at G:i','Wednesday, 8 January 2014 at 17:40'); 
echo $date->format('j F Y'); //"prints" 8 January 2014 
0

下面是簡單的代碼來獲得2014 1月8日給你:)

<?php 
    $txt = 'Wednesday, 8 January 2014 at 17:40'; 
preg_match('#(?<=,\s)\d{1,2}\s\w+\s\d{1,4}(?=\sat)#', $txt, $result); 
    ?>