0

I really should polish up on my regex but for now can anyone help with this...

((2,3,4,11,8),(5,44,67,78,32,22,111,234))

as you can see, each range of numbers is comma separated and, in this example, there are 2 ranges of of numbers.

In a live scenario there could be many numbers and a handful of ranges.

So... how do i extract something like this into a php nested array or something similar?

ANY help appreciated

1
  • 1
    Are they always nested at a depth of two? So, a single range of one number would be ((1)) - and three ranges of numbers, each three long, would look like ((1,2,3),(4,5,6),(7,8,9))? Commented Sep 13, 2010 at 18:45

2 Answers 2

5

Use explode() wisely and do it like this:

$ranges = '((2,3,4,11,8),(5,44,67,78,32,22,111,234))';

//break into groups
$array = explode('),(', $ranges);

//trim any parenthesis left and then split by comma ,
foreach($array as &$group)
    $group = explode(',',trim($group, '()'));

//display result
var_dump($array);

This outputs:

array
  0 => 
    array
      0 => string '2' (length=1)
      1 => string '3' (length=1)
      2 => string '4' (length=1)
      3 => string '11' (length=2)
      4 => string '8' (length=1)
  1 => &
    array
      0 => string '5' (length=1)
      1 => string '44' (length=2)
      2 => string '67' (length=2)
      3 => string '78' (length=2)
      4 => string '32' (length=2)
      5 => string '22' (length=2)
      6 => string '111' (length=3)
      7 => string '234' (length=3)
Sign up to request clarification or add additional context in comments.

Comments

3
$input = str_replace(array('(', ')'), array('[', ']'), $input);
$output = json_decode($input);

This might work as well

3 Comments

Needs to be $input = str_replace("(", "[", $input); and $input = str_replace(")", "]", $input);
maybe it's even possible to get the input in json from the start
the storage format is arbitrary. how would a JSON string look? I think the first str_replace could be changed to preg_replace to accommodate arrays.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.