在PHP中解析日期的字符串

nic*_*ckf 22 php datetime parsing nlp

给定一个任意字符串,例如("I'm going to play croquet next Friday""Gadzooks, is it 17th June already?"),你将如何从那里提取日期?

如果这看起来像是一个太难的篮子的好候选人,也许你可以建议一个替代方案.我希望能够解析Twitter消息的日期.我要查看的推文将是用户指导此服务的推文,因此可以使用更简单的格式进行指导,但我希望它尽可能透明.你能想到一个良好的中间立场吗?

Dol*_*lph 12

如果你有马力,你可以尝试以下算法.我正在展示一个例子,并将繁琐的工作留给你:)

//Attempt to perform strtotime() on each contiguous subset of words...

//1st iteration
strtotime("Gadzooks, is it 17th June already")
strtotime("is it 17th June already")
strtotime("it 17th June already")
strtotime("17th June already")
strtotime("June already")
strtotime("already")

//2nd iteration
strtotime("Gadzooks, is it 17th June")
strtotime("is it 17th June")
strtotime("17th June") //date!
strtotime("June") //date!

//3rd iteration
strtotime("Gadzooks, is it 17th")
strtotime("is it 17th")
strtotime("it 17th")
strtotime("17th") //date!

//4th iteration
strtotime("Gadzooks, is it")
//etc
Run Code Online (Sandbox Code Playgroud)

我们可以假设这strtotime("17th June")strtotime("17th")仅仅因为它包含更多单词更准确...即"下周五"将始终比"星期五"更准确.


Sco*_*ers 6

我会这样做:

首先检查整个字符串是否为strtotime()的有效日期.如果是这样,你就完成了.

如果没有,请确定字符串中有多少单词(例如,在空格上拆分).设这个数字是n.

循环遍历每个n-1个单词组合并使用strtotime()查看该短语是否为有效日期.如果是这样,您在原始字符串中找到了最长的有效日期字符串.

如果不是,则遍历每个n-2个单词组合并使用strtotime()来查看该短语是否是有效日期.如果是这样,您在原始字符串中找到了最长的有效日期字符串.

...等等,直到找到有效的日期字符串或搜索每个/单个单词.通过找到最长的匹配,您将获得最明智的日期(如果这是有道理的).由于你正在处理推文,你的字符串永远不会很大.