Created
April 7, 2013 23:37
-
-
Save timkinnane/5333114 to your computer and use it in GitHub Desktop.
Generate date range regex, PHP.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
function get_daterange_regex( $from, $to, $input_format ) { | |
// get the difference in months | |
$date1 = DateTime::createFromFormat( $from, $input_format ); | |
$date2 = DateTime::createFromFormat( $to, $input_format ); | |
$interval = $date1->diff($date2); | |
$months = $interval->m; | |
// get an array of the interveening months | |
$all_months = array(); | |
for ($i = 0; $i<=$months; $i ++) { | |
$all_months[$i] = $date1->modify('+1 month'); | |
} | |
$month_codes = array_map( 'acf_date_format', $all_months); | |
// return the regex string created from the array | |
return "/" . implode( "|", $month_codes ) . "/"; | |
} | |
function acf_date_format($date) { | |
return date_format($date, 'Ym'); | |
} | |
// e.g Get the regex string for finding posts between Dec 2011 and Mar 2012 | |
$date_regex = get_daterange_regex( '2011-12', '2012-03', 'Y-m' ); | |
// Outputs "/201112|201201|201202|201203/" depending on date formats given | |
echo $date_regex |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment