Domanda

I am trying to do a rough date validation for 13 Jun 1897 format with this but it keeps giving invalid no matter what date I input.

$date = $_GET['date'];
if (preg_match('/^[0-9]{1,2} [Jan|Feb|Mar|Apr|May|Jun|Jul|Aug|Sep|Oct|Nov|Dec] [0-9]{4}$/', $date)) {
    $date = date("Ymd", strtotime($date));
    echo $date;
}
else 
echo 'invalid';

To elaborate slightly, the date can be in that format, or Sep 1965 or just 1989. If the latter two I need to replace the missing values with zeros. eg. 19650900 or 19890000. So I first want to do a rough check and convert. If not valid I then need to manually replace the missing values with zeros. My complete code will look something like this:

function conv_date($date)
{
if (preg_match('/^[0-9]{1,2} [Jan|Feb|Mar|Apr|May|Jun|Jul|Aug|Sep|Oct|Nov|Dec] [0-9]{4}$/', $date))
    return date("Ymd", strtotime($date));

$date = str_replace('?',' ',$date);
$words = explode(' ', $date);
$year = array_pop($words);
$month = array_pop($words);
$day = array_pop($words);
if ($year < 1600 || $year > date("Y"))
    return '';
if (empty($day) || $day < '1' || $day > '31')
    $day = '00';
else
    $day = substr('0'.$day,-2);
if (!empty($month))
    $month = str_replace(array('Jan','Feb','Mar','Apr','May','Jun','Jul','Aug','Sep','Oct','Nov','Dec'),
                         array('01','02','03','04','05','06','07','08','09','10','11','12',),$month);
if ($month < '01' || $month > '12')
    $month = '00';
return $year.$month.$day;
}
È stato utile?

Soluzione

Use normal brackets instead of square:

(?:Jan|Feb|Mar|Apr|May|Jun|Jul|Aug|Sep|Oct|Nov|Dec)

I used ?: to make it non-capturing. Square brackets are used for the groups of symbols.

Altri suggerimenti

First off, you will need to use whitespace characters rather than spaces.

[\s]{1}

Second, it will not get Jan, it is looking at "J", "a", and "n". Try this.

see user4035's answer
Autorizzato sotto: CC-BY-SA insieme a attribuzione
Non affiliato a StackOverflow
scroll top