I tried searching for this both here and on Google, so if I missed something obvious, I apologize. It’s possible I simply don’t know the name for the formatting of these numbers.
What I’m looking to do is to start with a string, like “1-3,5,7-9” and have it turn into a PHP array with the following entries: 1,2,3,5,7,8,9
I know how to do this by using preg_split on a comma, then iterating through and expanding any – marks, but I feel like there must be an easier/better way.
EDIT
I didn’t make this clear, but the string needs to include SPANS! That means if my string was “1-9” my resulting array should be “1,2,3,4,5,6,7,8,9” NOT JUST “1,9”. Sorry for that not being clear before.
Not entirely sure what you mean by “expanding”. Anyway, here’s how I would do it with
explodeandrange:If there’s a better way that doesn’t use
eval(or PCREemodifier), I don’t know any.Here is, for your amusement, a one-liner (that unfortunately uses
eval) that returns the same result, but…Disclaimer: Using
evalis not recommended in most cases because it can create security risks and other issues. I wouldn’t use it but it’s still feasible.With that said, here it is: