开发者

regex problem for newbie ranges of numbers

开发者 https://www.devze.com 2023-01-16 12:44 出处:网络
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))

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


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)


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

This might work as well

0

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号