2010-02-07 114 views
1

我的表情不太好......我看過一些在線教程,但我仍然沒有得到它。基本上,我試圖返回TRUE如果一個字符串的格式如下:PHP - preg_match?

4位數字+空格+ 2位數並將其轉換爲日期。

所以,字符串看起來像:2010 02,我試圖輸出February, 2010

我試圖使用preg_match,但我不斷收到

{ is not a modifier...

編輯

每第2個反應,我改變了它,但我第一個得到一個致命的錯誤,在第二個相同的未知修飾符錯誤:

if(preg_match('/([0-9{4}]) ([0-9]{2})/iU',$path_part)) { 
    $path_title = date("F, Y",strtotime(str_replace(" ","-", $path_title))); 
} 

此外,只是嘗試更深入的杉木版本ST響應,同時錯誤消失,它不會改變輸出...

$path_part = '2010 02'; 
if(preg_match('/^(\d{4}) (\d{2})$/',$path_part,$matches)) { 
    $path_title = $mon[(int)$matches[2]] . " " . $matches[1]; // prints Feb 2010 
} 
+0

/([0-9 {4}])([0-9] {2})/是不正確。使用/([0-9] {4})([0-9] {2})/或 /(\ d {4})(\ d {2})/ – codaddict 2010-02-07 15:57:35

回答

3

我試圖返回TRUE,如果一個字符串格式是這樣的:4位+空格+ 2個位數

return preg_match(/^\d{4} \d{2}$/,$input); 

要轉換迄今爲止你可以嘗試這樣的:

$mon = array('','Jan','Feb','Mar','Apr','May','Jun','Jul','Aug','Sep','Oct','Nov','Dec'); 
$date_str = "2010 02"; 

if(preg_match('/^(\d{4}) (\d{2})$/',$date_str,$matches)) 
{ 
     print $mon[(int)$matches[2]] . " " . $matches[1]; // prints Feb 2010 
} 
+0

試過這個,但我得到一個致命語法錯誤... – phpN00b 2010-02-07 15:51:32

+0

請編輯您的問題併發布您的代碼。 – codaddict 2010-02-07 15:52:01

+0

好的,我剛剛做到了。我嘗試了更長時間的解釋,錯誤消失了,但它沒有輸出任何不同的東西。仍然打印出2010 02 – phpN00b 2010-02-07 15:58:02

0

試試這個...

preg_match('/([0-9{4}]) ([0-9]{2})/iU', $input); 
+0

這是錯的。第一個字符組與變體混合在一起。它應該是'[0-9] {4}'而不是 – 2010-02-07 15:49:55

+0

我試過了,我得到了同樣的錯誤: 警告:preg_match()[function.preg-match]:未知修飾符'{' – phpN00b 2010-02-07 15:52:15

0

在不具有任何細節作爲實際代碼,以下應該工作:

<?php 

$str = '2010 02'; 

$months = array('January', 'February', 'March', 'April', 'May', 'June', 'July', 'August', 'September', 'October', 'November', 'December'); 

if(preg_match('/([0-9]{4}) ([0-9]{2})/', $str, $match) == 1){ 
    $year = $match[1]; 
    $month = (int) $match[2]; 
    echo $months[$month - 1] . ', ' . $year; 
}else{ 
    //Error... 
} 

?> 
0
$in = "2010 02"; 
if(preg_match('/([0-9]{4}) ([0-9]{2})/i', $in, $matches)) { 
     echo date("F Y", strtotime($matches[2] . "/1/" . $matches[1])); 
}