2012-01-21 190 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_*函數之一。

相關問題