代码之家  ›  专栏  ›  技术社区  ›  phsource

在较长的消息中标识与日期相关的文本

  •  2
  • phsource  · 技术社区  · 15 年前

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

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

    然而,我一开始就很难找到那些日期。例如,在下面的字符串中,

    我明天晚上9点到那里吃晚饭

    我需要隔离“明天晚上9点”,因为这是strotime认识到的部分。

    2 回复  |  直到 13 年前
        1
  •  1
  •   netcoder    15 年前

    date_parse . 匹配的正则表达式 任何 接受的格式 strtotime

    $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
  •  0
  •   chaimp    15 年前

    这可能不是完全有效的,但应该适用于任何长度为5个单词的日期字符串。我会写函数,但我想你会得到下面的评论的想法。。。

    $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()
    
    推荐文章