在自由格式文本中查找日期的最佳方法是什么?用户可以通过多种不同方式在其中放置日期的帖子,例如:
- 7 月 14 日和 15 日
- 7/14 & 7/15
- 7-14 & 7-15
- 14 号星期六和 15 号星期日
- 7 月 14 日至 15 日星期六
等等。使用 preg_match
时,正则表达式是我的最佳选择吗?我还想搜索是否有两个日期,一个用于开始日期,第二个用于结束日期,但在我搜索的文本中可能有一个或两个日期。
到目前为止,这是我的 PHP 代码:
$dates1 = '01-01';
$dates2 = 'July 14th & 15th';
$dates3 = '7/14 & 7/15';
$dates4 = '7-14 & 7-15';
$dates5 = 'Saturday 14th and Sunday 15th';
$dates6 = 'Saturday July 14th and 15th';
$regexes = array(
'/\s(1|2|3|4|5|6|7|8|9|10|11|12)\/\d{1,2}/', //finds a date
'/\s(1|2|3|4|5|6|7|8|9|10|11|12)-\d{1,2}/', //finds another date
'%\b(0?[1-9]|[12][0-9]|3[01])[- /.](0?[1-9]|1[012])\b%', //finds date format dd-mm or dd.mm
);
foreach($regexes as $regex){
preg_match($regex,$dates,$matches);
}
var_dump($matches);
最佳答案
PHP 有一个名为 DateTime 的类来管理时间戳。它使您可以非常轻松地在字符串和 DateTime 对象之间进行转换...前提是您的字符串使用 PHP 提供的格式。
例如,
$date = DateTime::createFromFormat('d-m', '01-01');
$date = DateTime::createFromFormat('F d', 'July 14');
$date = DateTime::createFromFormat('d-M-Y', '15-Feb-2009');
也就是说,这是我要做的:
按优先顺序创建可接受格式的数组:
$formats = array("d-m", "j-M-Y" ... );
使用 RegEx 处理您的输入,使其与您的格式匹配。
// Add the current year to this one:
$dates1 = '01-01';
// Split these into "July 14" and "July 15", and add the year
// (this one will be the toughest)
$dates2 = 'July 14th & 15th';
// Split these into "7/14" and "7/15", and add the year
$dates3 = '7/14 & 7/15';
// Split these into "7-14" and "7-15", and add the year
$dates4 = '7-14 & 7-15';
// Split these, and add a month and year
$dates5 = 'Saturday 14th and Sunday 15th';
// Split these, and add a year:
$dates6 = 'Saturday July 14th and 15th';
尝试构造一个 DateTime 对象:
$date = false;
foreach ($formats as $format)
{
$date = DateTime::createFromFormat($format, $dateString);
if ($date) break;
}
关于php - 在自由格式文本中查找日期的最佳方法是什么?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/11424926/