【问题标题】:date in a paragraph [closed]段落中的日期[关闭]
【发布时间】:2014-03-24 01:28:44
【问题描述】:

比如有一个数据

$string = "我的生日是 2014 年 7 月 11 日"

如何获取字符串中的日期?

【问题讨论】:

  • 日期是否总是相同的格式?
  • 显示一些代码可能会更好,以便人们知道您也在做这项工作。编写一个使用正则表达式查找月份名称的函数。这是second result of my google search
  • 是的,它总是采用相同的格式 :)

标签: php


【解决方案1】:
$string = 'Mr Roux said it will be argued that on July 11 2014 it was physically impossible for Ms Steenkamp to have continued to scream after being struck in the head by a bullet from gun, especially if the sound had to travel 177 metres from the bathroom where the young model cowered.\"A person with that brain damage will have no cognitive response,\" he said.A short time later Dr Burger’s evidence was complete, herself fighting back tears at having to relive the night in question.\"It was awful to hear her shout before the shots,\" she said, saying she was still plagued by the screams. \"Its still quite raw.\" The Oscar Pistorius';

preg_match_all('/\b(?:Jan(?:uary)?|Feb(?:ruary)?|Mar(?:ch)?|Apr(?:il)?|May?|Jun(?:e)?|Jul(?:y)?|Aug(?:ust)?|Sept(?:ember)?|Oct(?:ober)?|Nov(?:ember)?|Dec(?:ember)?) (\d|\d{2}) \d{4}/', $string, $matches);

//flattens the array, because it is bi-dimensional
$flattened_array = new RecursiveIteratorIterator(new RecursiveArrayIterator($matches));

//loop through this flattened array
foreach($flattened_array as $k => $v)
{
        //if the value of that array item is not a pure integer (11 or 12, etc..)
    if((int) $v === 0)
    {
            //add the value to the final output array
        $final_matches[] = $v;
    }       
}

var_dump($final_matches);
//returns array(2) { [0]=> string(12) "July 11 2014" [1]=> string(12) "July 12 2014" }

正则表达式将匹配 Jan(uary)、Feb(ruary)、Mar(ch) 等...后跟空格,然后是 X 或 XX(数字),然后是空格,然后是 XXXX。

p>

【讨论】:

  • 第 1-9 天?不太可能在印刷品中看到July 01 2014 更有可能是July 1 2014
  • @Dagon 谢谢。我已经更新了上面的答案。
  • 好的,但 8000 年后这将失败 :-)
  • :P ...如果这恰好是 OP 应用程序中唯一需要在 8000 年后更改的代码行,那么他将成为世界上最好的开发人员,而我想给他/她买杯啤酒。
  • 它又得到了 11 个?
猜你喜欢
  • 2018-08-02
  • 2015-11-13
  • 2012-01-13
  • 2022-01-25
  • 1970-01-01
  • 2012-10-21
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多