views:

139

answers:

2

I have a website where I need to parse date/time strings from receipts. These can be in a variety of different formats -- for instance, one string could be '11/04/2009 12:46PM', while another could be 'Mar06'09 10:57AM'. I need to get a standard date/time string out of them to do a database insert.

I'd like to avoid writing new php code for each client to parse their string. Something I do elsewhere is store a regular expression in a database field -- that way, in order to validate data, I can just do

<?php

if ( ! preg_match($row['regex'], $variable_user_input) ) { ... }

?>

So if I need to add a client that has a different validation criteria, I just have to write a new regex, which goes in the client database record, instead of writing, testing, and deploying new php code on the website. It's a more robust system.

Is there something like a regular expression, when I can input a string, input another transformation string, and get my date-time as output?

+2  A: 

This doesn't handle the regex portion, but I bet strtotime will come into play at some point in the process.

easement
+2  A: 

you can use named subgroups in your regular expressions to decouple the parser from concrete formats

function parse_date($date, $regexps) {
     foreach($regexps as $re)
  if(preg_match($re, $date, $m))
      return strtotime("{$m['year']}-{$m['month']}-{$m['day']} {$m['time']}");
}


$formats = array(
 "~(?P<month>[a-z]+)(?P<day>\d\d)'(?P<year>\d\d) +(?P<time>[\d:APM]+)~i",
 "~(?P<month>\d\d)/(?P<day>\d\d)/(?P<year>\d\d\d?\d?) +(?P<time>[\d:APM]+)~i"
);


echo date("d m Y H i", parse_date("Mar06'09 10:57AM", $formats));
echo date("d m Y H i", parse_date('11/04/2009 12:46PM', $formats));

// edit

named patterns are quite sparsely documented, this is all i could find

It is possible to name the subpattern with (?Ppattern) since PHP 4.3.3. Array with matches will contain the match indexed by the string alongside the match indexed by a number, then.

http://www.php.net/manual/en/regexp.reference.subpatterns.php

stereofrog
Thanks, stereofrog! Can you point me to a tutorial for named subgroups? A google search doesn't turn up much -- just references on mailing lists.
post edited............
stereofrog