Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

PHP: Is there a simple way to parse a list of numbers (as a string, like "1-3,5,7-9") into an array?

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.

like image 631
Bing Avatar asked Oct 19 '11 18:10

Bing


1 Answers

Not entirely sure what you mean by "expanding". Anyway, here's how I would do it with explode and range:

$input = '1-3,5,7-9';
$output = array();

foreach (explode(',', $input) as $nums) {
    if (strpos($nums, '-') !== false) {
        list($from, $to) = explode('-', $nums);
        $output = array_merge($output, range($from, $to));
    } else {
        $output[] = $nums;
    }
}

If there's a better way that doesn't use eval (or PCRE e modifier), 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 eval is 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:

$output = explode(',', preg_replace('/([0-9]*)-([0-9]*)/e', 'implode(",", range($1, $2));', $input));
like image 155
netcoder Avatar answered Oct 17 '22 06:10

netcoder