How to reduce lists of ranges?

Nana64

New Member
Given a list of ranges ie: \[code\]1-3,5,6-4,31,9,19,10,25-20\[/code\]how can i reduce it to \[code\]1-6,9-10,19-25,31\[/code\] ?Here is what i've done so far, it seems a little bit complicated, sois there any simpler/clever method to do this.\[code\]$in = '1-3,5,6-4,31,9,19,10,25-20';// Explode the list in ranges$rs = explode(',', $in);$tmp = array();// for each range of the listforeach($rs as $r) { // find the start and end date of the range if (preg_match('/(\d+)-(\d+)/', $r, $m)) { $start = $m[1]; $end = $m[2]; } else { // If only one date $start = $end = $r; } // flag each date in an array foreach(range($start,$end) as $i) { $tmp[$i] = 1; }}$str = '';$prev = 999;// for each date of a month (1-31)for($i=1; $i<32; $i++) { // is this date flaged ? if (isset($tmp[$i])) { // is output string empty ? if ($str == '') { $str = $i; } else { // if the previous date is less than the current minus 1 if ($i-1 > $prev) { // build the new range $str .= '-'.$prev.','.$i; } } $prev = $i; }}// build the last rangeif ($i-1 > $prev) { $str .= '-'.$prev;}echo "str=$str\n";\[/code\]NB: it must run under php 5.1.6 (i can't upgrade).FYI : the numbers represent days of month so they are limited to 1-31.Edit:From a given range of dates \[code\](1-3,6,7-8)\[/code\], i'd like obtain another list \[code\](1-3,6-8)\[/code\] where all the ranges are recalculated and ordered.
 
Back
Top