加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 站长学院 > PHP教程 > 正文

php – 英语到时间

发布时间:2020-12-13 13:10:06 所属栏目:PHP教程 来源:网络整理
导读:有没有人知道一个好的类/库将时间的英文表示转换成时间戳? 目标是转换自然语言短语,例如“从现在起十年”,“三周”和“在十分钟内”,并为他们制定最佳匹配unix时间戳. 我已经破解了一些非常糟糕且未经测试的代码以便继续使用它,但我确信有很好的解析器可用
有没有人知道一个好的类/库将时间的英文表示转换成时间戳?

目标是转换自然语言短语,例如“从现在起十年”,“三周”和“在十分钟内”,并为他们制定最佳匹配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
  }

}

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读