2012-01-21 193 views
2

我试图抓住表示日期的字符串的一部分。正则表达式来从字符串中获取日期

日期字符串通常但不总是在其之前和/或之后具有常规文本。

在这个例子中:

Sometimes text is here, Sun, Apr 09, 2000 And sometimes but not always text here 

我希望得到的结果是:

Sun, Apr 09, 2000 

记住,天,月弦的长度可以是3个或4个字符。

我微薄的尝试是:

$test = "Sometimes text is here, Sun, Apr 09, 2000 And sometimes but not always text here"; 

if (ereg ("/([a-z]{3,4}),.([a-z]{3,4}).([0-9]{1,2}),.([0-9]{4})/i", $test, $regs)) { 
    echo "$regs[4].$regs[3].$regs[2].$regs[1]"; 
} 

同样乐于基于非正则表达式的解决方案。

回答

1

此正则表达式似乎在多种情况下的工作:

$str = "Sometimes text is here, Sun, Apr 09, 2000 And sometimes but not always text here"; 
$reg = '/(\w{3}),\s*(\w{3})\s*(\d+),\s*(\d{4})/'; 

$match = preg_match($reg, $str, $matches); 

if ($match) { 
    $date = "{$matches[2]} {$matches[3]} {$matches[4]}\n"; 
    // Apr 09 2000 
    $timestamp = strtotime($date); 
} 

ereg()不应再使用,因为PHP 5.3.0的被弃用,预浸一直被看好是一种更快,更广泛地使用替代。

1

不要依赖于已弃用的ereg,请尝试preg_match_all

$str = "Sometimes text is here, Sun, Apr 09, 2000 And sometimes but not always text here"; 

preg_match_all('/.*([A-Za-z]{3,4}, [A-Za-z]{3,4} [\d]{1,2}, [\d]{4}).*/',$str,$matches); 

输出

(
    [0] => Array 
     (
      [0] => Sometimes text is here, Sun, Apr 09, 2000 And sometimes but not always text here 
     ) 

    [1] => Array 
     (
      [0] => Sun, Apr 09, 2000 
     ) 

) 

你会发现所有的比赛中$matches[1]

2

有人也许可以做得比这更好,因为这是很冗长:

/(?:mon|tues?|weds|thurs?|fri|sat|sun), [a-z]{3,4} [0-9]{1,2}, [0-9]{4}/i 

$regex = '/(?:mon|tues?|weds|thurs?|fri|sat|sun), [a-z]{3,4} [0-9]{1,2}, [0-9]{4}/i'; 
$string = 'Sometimes text is here, Sun, Apr 09, 2000 And sometimes but not always text here'; 

preg_match($regex, $string, $matches); 

echo $matches[0]; 
// Sun, Apr 09, 2000 

如果你期待出现多次的日期,一个微小的变化有所帮助。

// store the match as a named parameter called 'date' 
$regex = '/(?<date>(?:sun|mon|tues?|weds|thurs?|fri|sat|sun), [a-z]{3,4} [0-9]{1,2}, [0-9]{4})/i'; 

$string = 'Sometimes text is here, Sun, Apr 09, 2000 And sometimes but not always text here. Sun, Mar 10, 2010'; 

preg_match_all($regex, $string, $matches); 

print_r($matches['date']); 
/* 
Array 
    (
     [0] => Sun, Apr 09, 2000 
     [1] => Sun, Mar 10, 2010 
    ) 
*/ 

以当天的名字开始,只是有可能得到的东西看起来与一天中的相同但不是。

我也不建议使用ereg(),因为它在5.3.0中已被弃用。改为使用preg_match(),或使用其他preg_*函数之一。

相关问题