tags:

views:

68

answers:

2

Hi All,

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

+5  A: 

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)
shamittomar
+3  A: 
$input = str_replace(array('(', ')'), array('[', ']'), $input);
$output = json_decode($input);

This might work as well

dave
+1 Clever solution!
Daniel Vandersluis
Needs to be `$input = str_replace("(", "[", $input);` and `$input = str_replace(")", "]", $input);`
Rocket
stupid array "literals" in php
hop
maybe it's even possible to get the input in json from the start
hop
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.
khany