What would be the best approach to finding a date in a freeform text?

Posted by Matthew DeVos on Stack Overflow See other posts from Stack Overflow or by Matthew DeVos
Published on 2012-07-11T03:00:13Z Indexed on 2012/07/11 3:15 UTC
Read the original article Hit count: 154

Filed under:
|
|
|

What would be the best approach to finding a date in a freeform text? A post where a user may place a date in it in several different ways such as:

  1. July 14th & 15th
  2. 7/14 & 7/15
  3. 7-14 & 7-15
  4. Saturday 14th and Sunday 15th
  5. Saturday July 14th and 15th

and so on. Is regex my best choice for this type of thing with preg_match? I would also like to search if there are two dates, one for a start date and a second for an end date, but in the text I'm searching there may be one date or two.

This is my PHP code so far:

$dates1 = '01-01';
$dates2 = 'July 14th & 15th';
$dates3 = '7/14 & 7/15';
$dates4 = '7-14 & 7-15';
$dates5 = 'Saturday 14th and Sunday 15th';
$dates6 = 'Saturday July 14th and 15th';

$regexes = array(
        '/\s(1|2|3|4|5|6|7|8|9|10|11|12)\/\d{1,2}/',  //finds a date
        '/\s(1|2|3|4|5|6|7|8|9|10|11|12)-\d{1,2}/',  //finds another date
        '%\b(0?[1-9]|[12][0-9]|3[01])[- /.](0?[1-9]|1[012])\b%', //finds date format dd-mm or dd.mm
        );
foreach($regexes as $regex){
preg_match($regex,$dates,$matches);
}
var_dump($matches);

© Stack Overflow or respective owner

Related posts about php

Related posts about regex