Search code examples
phpregexpreg-match

preg_match strings regardless of proper format


I have this kind of string format used in a preg_match:

[Day][MonthAbbr] [Date] [Hour]:[Minutes][AM/PM]

example:
ThuDec 27 2:00am

Having this $pattern and some sort of code:

$pattern = "/([A-Z]{2}\w+)([A-Z]{2}\w+)\s+(\w+)\s+(\d+):(\d+)(..)/ims";
$match = array();
if (preg_match($pattern, rtrim($date), $match)) {
    echo '<pre>';
        print_r($match);
    echo '</pre>';
} else {
    echo 'Could not parse date.';
}

i was able to extract the Month, Day, Time, etc... from the string..

But i was wondering why i came up with the catch 'Could not parse date.' even if the value being passed was still the same..

I compared the values and the one which has an error:

ThuDec 27 2:00am
ThuDec 27  4:30am (gives the error)

Here's the screen shot below to make a comparison:

As you can see, it returns empty array!

Is there something wrong with the pattern ive been using in the preg_match?


Solution

  • <?php
    $a = "ThuDec 27  4:30am";
    $pattern = "/([a-z]{3})([a-z]{3})\s+(\d+)\s+(\d+):(\d+)([a-z]{2})/i";
    $match = array();
    if (preg_match($pattern, $a, $match)) {
        echo '<pre>';
            print_r($match);
        echo '</pre>';
    } else {
        echo 'Could not parse date.';
    }
    ?>
    

    This code works pretty well for me.