I want to translate/hydrate/expand/parse a comma-separated string of integers and hyhenated integer range expressions and populate an array with its equivalent values as individual integers elements.
Input strings might look like the following:
3,5,6,9,11,23
or
3-20
or
3-6,8,12,14-20
I want to return these as an array of integers, so the last one would become:
[3,4,5,6,8,12,14,15,16,17,18,19,20]
Is there either a function available that does this, or how would I start in writing one?
You are probably looking for the
rangefunction andimplode:gives you:
Demo
How it works: You basically have two tokens in your string: the range-token
(1-n)(defined as regular expression:(\d+)-(\d+)) and the fallback (anything else).preg_replace_callbackallows the expansion of the token string by a callback function. That callback function then just expands the two matched numerical values into the comma-separated list by using PHP’srangefunction andimplode.After that the string is in a normalized format you can just
explodeit:Full Demo
And after years as it was requested well formulated, the integer array, you can easily treat it as a JSON Array:
Demo PHP 5.3-8.1 + Git Master