Welcome Guest, Not a member yet? Register   Sign In
RegEx trouble
#1

[eluser]Fabdrol[/eluser]
Hi folks

I'm checking a date string in the foll format, generated by js and put in a form field:
Code:
YYYY-MM-DD HH:II

I cannot use form_valid lib on this, so I need to check it myself. To do so I have the following preg_match:
Code:
if(preg_match("([0-9]{4})-([0-9]{1,2})-([0-9]{1,2}) ([0-9]{1,2}):([0-9]{1,2})", $start) !== false) {
// do stuff
}
But somehow I can't recreate a 'wrong' situation. Is this a correct RegEx for checking this? I'm really bad at RexExes....

Thnks in advance
#2

[eluser]Cro_Crx[/eluser]
http://php.net/manual/en/function.preg-match.php

Check the return section. It returns 0 if there's no matches. So it will never === false. You can either compare against 0 instead of false, or just use == instead of triple.

I think there might be another PHP regex function that will return false for no matches, although can't remember which one. If you google it, you'll probably get it.

Update

Your regex looks fine although it will allow single digits in some parts, so This will pass as correct 2010-1-3 2:3

Usually you'd want 2 digits both the hours and minute, so the regex would be:
Code:
"([0-9]{4})-([0-9]{1,2})-([0-9]{1,2}) ([0-9]{2}):([0-9]{2})"

But if you want the above time to pass then no need to alter it!
#3

[eluser]sophistry[/eluser]
hi,

you need pattern delimiters like '/pattern/'...

also, please look at this page for a great resource on regex (direct link to date detection regex):

http://www.regular-expressions.info/dates.html
#4

[eluser]Fabdrol[/eluser]
Okay, thank you very much :-)
It's clear to me now Tongue




Theme © iAndrew 2016 - Forum software by © MyBB