views:

557

answers:

4

I'm not very good with expressions... I've looked at some online tutorials, but I'm still not getting it. Basically, I'm trying to return TRUE if a string is formatted like this: 4 digits + space + 2 digits and convert it to a date.

So, the string will look like: 2010 02, and I'm trying to output February, 2010.

I'm trying to use preg_match, but I keep getting { is not a modifier...

EDIT

Per the first 2 responses, I changed it, but am getting a fatal error on the first and the same unknown modifier error on the second:

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

Also, just tried the more in-depth version in the first response, and while the error goes away, it doesn't change the output...

$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
                }
+3  A: 

I'm trying to return TRUE if a string is formatted like this: 4 digits + space + 2 digits

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

To convert to date you can try something like:

$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
}
codaddict
Tried this, but I get a fatal syntax error...
phpN00b
please edit your question and post your code.
codaddict
Ok, I just did. I tried the longer explanation and the errors go away, but it doesn't output anything different. Still prints out 2010 02
phpN00b
You need to ensure that the number of the month is only in the valid range of 1..12.
Gumbo
A: 

Try this one...

preg_match('/([0-9{4}]) ([0-9]{2})/iU', $input);
rATRIJS
This one's wrong. The first character group is mixed up with the mutliplier. It should be `[0-9]{4}` instead
Cassy
I tried this, and I get the same error:warning: preg_match() [function.preg-match]: Unknown modifier '{'
phpN00b
A: 

Without having any detail as to your actual code, the following should work:

<?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...
}

?>
Stephen Cross
A: 
$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]));
}
bmb