2017-03-31 52 views
0

裏面我有一個字符串是這樣的:PHP的獲得日期字符串

Lorem存有悲坐阿梅德,consectetuer adipiscing ELIT。 Aenean 2017-03-31 ligula eget dolor。 Aenean馬薩。 2016-03-04 sociis natoque penatibus ...

我想獲得文本中的所有日期...格式日期總是yyyy-mm-dd

有什麼建議嗎?

+10

在[所以]你應該嘗試**自己編寫代碼**。後** [做更多的研究](//meta.stackoverflow.com/questions/261592)**如果你有問題,你可以**發佈你已經嘗試**與清楚的解釋是什麼是'工作**並提供[** Minimal,Complete和Verifiable示例**](// stackoverflow.com/help/mcve)。我建議閱讀[問]一個好問題和[完美問題](http://codeblog.jonskeet.uk/2010/08/29/writing-the-perfect-question/)。另外,一定要參加[旅遊]。 –

+1

嘗試正則表達式,獲取正確的模式以匹配日期,然後在preg_match函數中使用該模式,請參閱http://php.net/manual/en/function.preg-match.php –

回答

1

嘗試使用的preg_match和正則表達式:

$string = "Lorem ipsum dolor sit amet, consectetuer adipiscing elit. Aenean 2017-03-31 ligula eget dolor. Aenean massa. 2016-03-04 sociis natoque penatibus..."; 
$pattern = '/([0-9]{4}-[0-9]{2}-[0-9]{2})/'; 
preg_match_all($pattern, $string, $matches); 
print_r($matches); 

爲了測試正則表達式,我建議你使用https://regex101.com/

+0

/g將不起作用在PHP中,使用preg_match_all –

1

好的,你要做的是找出你正在試圖找到的東西,在你的情況下yyyy-mm-dd

因此,這將是它:

[0-9]{4}-[0-9]{2}-[0-9]{2} 
1
preg_match("/[0-9]{4}-[0-9]{1,2}-[0-9]{1,2}/", $input_line, $output_array);