Question

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
}
Was it helpful?

Solution

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
}

OTHER TIPS

Try this one...

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

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

?>
$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]));
}

You can also use T-Regx library

$string = '2010 02';

pattern('\d{4} \d{2}')->match($string)->first(function (Match $match) 
{
    $year = $match->group(1);
    $month = $match->group(2);
});
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top