【问题标题】:Identify date-related text in a longer message识别较长消息中与日期相关的文本
【发布时间】:2010-11-15 20:08:32
【问题描述】:

我目前正在编写一个脚本,该脚本将从消息中提取所有日期并将它们转换为时间戳。 PHP 的 strtotime(类似于 Unix 的 date -c 'some date')非常适合这一点,因为它可以识别各种日期,例如:

  • 今天下午 5 点
  • 2010-11-15 16:30
  • 星期四 8:00

但是,我一开始就很难找到这些日期。例如,在以下字符串中,

我明天晚上 9:00 去那里吃晚饭

我需要隔离“明天晚上 9:00”,因为这是 strtotime 识别的部分。

是否有正则表达式或类似的东西可以返回所有可以被 strtotime 解析的日期?

【问题讨论】:

  • 这个问题可能会有所帮助:stackoverflow.com/questions/3845145/…
  • 希望你没有和法国语言决斗,像novembre 这样的东西可能会让你的正则表达式工作标题
  • 最有帮助的答案是 rojoca 的链接;我设法破解了一个类似的正则表达式

标签: php datetime


【解决方案1】:

我唯一能想到的是date_parse。匹配strtotime 接受的任何 格式的正则表达式将非常庞大。

date_parse 的一个例子:

$str = "I'll be there for dinner tomorrow at 9:00pm";
$parsed = date_parse($str);
print_r($parsed);

它会输出类似这样的东西(我从中删除了不重要的部分以使其结果更轻):

Array
(
    [year] => 
    [month] => 
    [day] => 
    [hour] => 21               // 9:00pm
    [minute] => 0              // 9:00pm  
    [second] => 0              // 9:00pm
    [fraction] => 0
    [warning_count] => 1
    [is_localtime] => 1
    [zone_type] => 2
    [zone] => -540
    [is_dst] => 
    [tz_abbr] => I
    [relative] => Array
        (
            [year] => 0
            [month] => 0
            [day] => 1          // tomorrow (would be -1 for yesterday, etc.)
            [hour] => 0
            [minute] => 0
            [second] => 0
        )

)

这是否适合您主要取决于您输入的内容。如果您的输入字符串中有多个日期实例,它将无法按预期工作。

【讨论】:

  • 是的,不幸的是,我确实需要处理多个日期实例。
【解决方案2】:

这可能不是完全有效,但应该适用于长度不超过 5 个单词的任何日期字符串。我会写这个函数,但我想你会通过下面的 cmets 明白这个想法......

$words = explode(' ',$original_string);

// Use the array_chunk() function break up this array into 1-word,
// 2-word, 3-word, and 4-word long substrings of the original string

// Reform them back into strings and pass each one through strtodate()

【讨论】:

  • 如果你的原始字符串是 N 字长,你最终会调用 strtodate() 不到 5*N 次。如果您查找最多 6 个字长的子字符串,则为 6*N 次,等等。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2013-05-16
  • 1970-01-01
  • 1970-01-01
  • 2013-02-05
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多