digitalnature / php-ref

A better alternative to print_r / var_dump
347 stars 59 forks source link

Better regex matching of date & datetime. #42

Open cirdog opened 7 years ago

cirdog commented 7 years ago

http://rgxdb.com/r/526K7G5W

/^(?:[+-]?\d{4}(?!\d{2}\b))(?:(-?)(?:(?:0[1-9]|1[0-2])(?:\1(?:[12]\d|0[1-9]|3[01]))?|W(?:[0-4]\d|5[0-2])(?:-?[1-7])?|(?:00[1-9]|0[1-9]\d|[12]\d{2}|3(?:[0-5]\d|6[1-6])))(?:T\s?|24\:?00)(?:[.,]\d+(?!:))?)?(?:\2[0-5]\d(?:[.,]\d+)?)?(?:[zZ]|(?:[+-])(?:[01]\d|2[0-3]):?(?:[0-5]\d)?)?)?)?$/

This regex above is supposed to match ISO-8601 dates and I suppose that it's better at identifying date strings than the original code. I was prompted to add this better-date-matching since the current code mis-identified a "HK phone number with center-blank-separator" (1234 5678) as dates and it bugged me.

protected $iso_8601 = '/^(?:[\+-]?\d{4}(?!\d{2}\b))(?:(-?)(?:(?:0[1-9]|1[0-2])(?:\1(?:[12]\d|0[1-9]|3[01]))?|W(?:[0-4]\d|5[0-2])(?:-?[1-7])?|(?:00[1-9]|0[1-9]\d|[12]\d{2}|3(?:[0-5]\d|6[1-6])))(?:[T\s](?:(?:(?:[01]\d|2[0-3])(?:(:?)[0-5]\d)?|24\:?00)(?:[\.,]\d+(?!:))?)?(?:\2[0-5]\d(?:[\.,]\d+)?)?(?:[zZ]|(?:[\+-])(?:[01]\d|2[0-3]):?(?:[0-5]\d)?)?)?)?$/';
if(($length < 128) && static::$env['supportsDate'] && preg_match($this->iso_8601, $subject) && !preg_match('/[^A-Za-z0-9.:+\s\-\/]/', $subject)){

If the author don't mind, please add this to your fantastic work. If no one issue any pull request, at least users of this piece of code can add the regex themselves.

Thanks.

prohtex commented 5 years ago

I'd really like to see unix epoch times recognized!