php - 在自由格式文本中查找日期的最佳方法是什么?

标签 php regex perl date

在自由格式文本中查找日期的最佳方法是什么?用户可以通过多种不同方式在其中放置日期的帖子,例如:

  1. 7 月 14 日和 15 日
  2. 7/14 & 7/15
  3. 7-14 & 7-15
  4. 14 号星期六和 15 号星期日
  5. 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/

相关文章:

php - 复杂查询中的计数

php - 共享主机中的Codeigniter应用程序无法连接到vps中的远程mysql

regex - Emacs lisp 转义正则表达式

perl - 为什么这些时间戳与 Perl Time::HiRes 不一致?

php - 如果存在某些值,则 mysql 更新,否则创建一个新条目

php - div 在 php 中 while 循环

java - Java中的字符串模式匹配问题

regex - 如何在 Perl 中找到与正则表达式的所有匹配项?

linux - 通过终端将 cat 结果中的确切内容替换为文件

regex - 误解 perl regexp 评估