php – 英语到时间

前端之家收集整理的这篇文章主要介绍了php – 英语到时间前端之家小编觉得挺不错的,现在分享给大家,也给大家做个参考。
有没有人知道一个好的类/库将时间的英文表示转换成时间戳?

目标是转换自然语言短语,例如“从现在起十年”,“三周”和“在十分钟内”,并为他们制定最佳匹配unix时间戳.

我已经破解了一些非常糟糕且未经测试的代码以便继续使用它,但我确信有很好的解析器可用于日历等.

private function timeparse($timestring)
{
    $candidate = @strtotime($timestring);
    if ($candidate > time()) return $candidate; // Let PHP have a bash at it

    //$thisyear = date("Y");
    if (strpos($timestring,"min") !== false) // Context is minutes
    {
            $nummins = preg_replace("/\D/","",$timestring);
            $candidate = @strtotime("now +$nummins minutes");
            return $candidate;
    }

    if (strpos($timestring,"hou") !== false) // Context is hours
    {
            $numhours = preg_replace("/\D/",$timestring);
            $candidate = @strtotime("now +$numhours hours");
            return $candidate;
    }

    if (strpos($timestring,"day") !== false) // Context is days
    {
            $numdays = preg_replace("/\D/",$timestring);
            $candidate = @strtotime("now +$numdays days");
            return $candidate;
    }

    if (strpos($timestring,"year") !== false) // Context is years (2 years)
    {
            $numyears = preg_replace("/\D/",$timestring);
            $candidate = @strtotime("now +$numyears years");
            return $candidate;
    }

    if (strlen($timestring) < 5) // 10th || 2nd (or probably a number)
    {
            $day = preg_replace("/\D/",$timestring);
            if ($day > 0)
            {
                    $month = date("m");
                    $year = date("y");
                    return strtotime("$month/$day/$year");
            }
            else
            {
                    return false;
            }
    }

    return false; // No can do.
}
使用 DateTime类.

例如.:

$string='four days ago';
$d=date_create($string);
$d->getTimestamp();

ETA:
您可以扩展:

class myDateTime extends DateTime {
  static $defined_expressions=array(...);

  function __construct($expression=NULL) {
     if ($exp=$this->translate($expression)) {
       parent::__construct($exp); 
     }
  }

  function translate($exp) {
     //check to see if strtotime errors or not
     //if it errors,check if $exp matches a pattern in self::$defined_expressions
     return $exp,modified $exp or false
  }

}
原文链接:https://www.f2er.com/php/136559.html

猜你在找的PHP相关文章