2010-02-07 219 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])); 
}