棘手。一种方法可能是推断日期总是出现在某些语法词之后,如您的示例所示,例如“between”、“on”等。使用这样的词作为开始锚点,然后我们将匹配,直到我们找到我们可以合理假设为日期字符串的结尾。这是我一起破解的:
//some strings
$strs = [
"Company was in business between 14 March 2008 and 21 November 2012 inclusive",
"I was born on 29 May 1980, 17:37 - it was a Thursday",
"The big bang did not occur at 2pm, 14 Jun 1971, that's for sure."
];
//container to store possible date matches from strings
$possible_dates = array();
//prep months - long and short forms, to be used in matching
$date_prefix_words = array('between', 'on', 'at', 'during', 'and');
$months = array('January', 'February', 'March', 'April', 'May', 'June', 'July', 'August', 'September', 'October', 'November', 'December');
$months_short = array_map(function($month) { return substr($month, 0, 3); }, $months);
//iterate over and search strings - convert times like 2pm to 14:00, as, if they appear before the date, e.g. string 3, it doesn't get parsed
foreach($strs as $str) {
$str = preg_replace_callback('/\b\d{1,2}[ap]m\b/', function($time) { return date('H:i', strtotime($time[0])); }, $str);
preg_match_all('/(?<=\b'.implode('\b( |:)|\b', $date_prefix_words).'\b( |:))(\d|am|pm| |,|\'|:|'.implode('|', $months).'|'.implode('|', $months_short).')+/i', $str, $matches);
if (count($matches)) $possible_dates = array_merge($possible_dates, $matches[0]);
}
//output before and after results
foreach($possible_dates as &$pd) {
$pd = preg_replace('/, ?$/', '', $pd);
echo '<p>Before: '.$pd.'<br />After: '.date('Y-m-d', strtotime($pd)).'</p>';
}
显然,我对您的日期格式做出了某些假设,您可能需要调整 REGEX,但它确实有效。