我有这个代码。我想在字符串中提取2014年1月1日,但我一直在变为空
$paragraph = "today is 2014 January 1";
preg_match_all('/(\d{4}/) \b(?:Jan(?:uary)?|Feb(?:ruary)?|Mar(?:ch)?|Apr(?:il)?|May?|Jun(?:e)?|Jul(?:y)?|Aug(?:ust)?|Sept(?:ember)?|Oct(?:ober)?|Nov(?:ember)?|Dec(?:ember)?) (\d|\d{2}) ', $paragraph, $date);
var_dump($date);
但var_dump($ date)返回null
答案 0 :(得分:0)
尝试以下操作,您只需对正则表达式进行一些调整。
$paragraph = "today is 2014 January 1, and tomorrow will be 2015 March 12";
$date = Array();
// Find all dates
preg_match_all('@((?:\d{4}) (?:Jan(?:uary)?|Feb(?:ruary)?|Mar(?:ch)?|Apr(?:il)?|May?|Jun(?:e)?|Jul(?:y)?|Aug(?:ust)?|Sept(?:ember)?|Oct(?:ober)?|Nov(?:ember)?|Dec(?:ember)) (?:\d{1,2}))@', $paragraph, $date);
// Display results
echo '<pre>';
print_r($date[0]);
echo '</pre>';
// Iterate over the results
$total = count($date[0]);
for($i=0;$i<$total;$i++){
// Use the following if you want to change the display format
date_create_from_format('Y-M-d', $date[0][$i]);
echo $date[0][$i].'<br />';
}
答案 1 :(得分:0)
您可以使用DateTime::createFromFormat()
作为示例,但是您需要转义每个字符,因为今天文本不代表日期格式。
<?php
$paragraph = "today is 2014 January 1";
$date = DateTime::createFromFormat('\t\o\d\a\y \i\s Y F j', $paragraph);
echo $date->format('Y F j'); //"prints" 2014 January 1