Simple code :
- split string by delimiter
,
with explode()
;
- remove space from the beginning and end of a string with
trim
;
- function
array_map
is used so you don't need to do foreach
loop just to apply trim()
to every element;
- create empty array where you will store new elements;
- iterate over each number or range with
foreach
;
- do points 1., 2. and 3. again on every iteration;
- split string by delimiter
-
with explode()
even if string doesn't have delimiter -
in it; result will be array with one or multi elements;
- if point 6. has array with multiple elements, that means that there is range involved, so use function
range()
to create an array containing a range of elements;
- store new numbers to point 4. array with
array_merge()
function;
- when point 4. array is full generated; sort values with
sort()
, so you don't have output like 5, 3, 1, 4
etc. (delete this function if you don't need this functionality);
- remove duplicates with
array_unique()
, so you don't have output like 4, 4, 4, 4, 5
etc. (delete this function if you don't need this functionality)
- to convert array back to string like you inputed, use
implode()
function.
|
function fillGaps($s) {
$s = array_map('trim', explode(',', $s));
$ss = [];
foreach ($s as $n) {
$n = array_map('trim', explode('-', $n));
if (count($n) > 1) $n = range($n[0], end($n));
$ss = array_merge($ss, $n);
}
sort($ss); # remove if you don't need sorting
$ss = array_unique($ss); # remove if duplicates are allowed
return implode(', ', $ss);
}
Example :
Your example :
echo fillGaps('1, 4, 7, 20 - 25, 31, 46, 100');
# 1, 4, 7, 20, 21, 22, 23, 24, 25, 31, 46, 100
This code will also work for multiple gaps, like :
echo fillGaps('100-105-110');
# 100, 101, 102, 103, 104, 105, 106, 107, 108, 109, 110
You can even go reverse :
echo fillGaps('10-5');
# 5, 6, 7, 8, 9, 10
# or remove function sort() and output will be 10, 9, 8, 7, 6, 5
Remove duplicates :
echo fillGaps('2-4, 4, 4, 5');
# 2, 3, 4, 5