php - Regex for extracting nested parameters in brackets -


i find proper regexp / recursive algorithm extract data string brackets.

$input = "0a,0b(1a((3a, 3b, 3c)))"; 

expected result:

[    0 => ["0a", "0b"],    1 => ["1a"],    2 => [],    3 => ["3a", "3b", "3c"]  ]; 

the following function pretty close, however, not detect empty data when there nested brackets, array has size of 3 instead of 4:

function extractparameters($line, &$params, $level = 0){     $pattern = "/([a-za-z0-9,:]+)(?:\((.+)?\))?/" ;     $matches = [] ;      preg_match($pattern, $line, $matches);      //we have valid value     if (isset($matches[1])){         $set = $matches[1] ;         $params[$level] = explode(",", $set);          //it has content         if (isset($matches[2])){             $content = $matches[2] ;             extractparameters($content, $params, ++$level);         }     } }  $input = "0a,0b(1a((3a,3b,3c)))" ; $params = []; extractparameters($input, $params); var_dump($params); 

here possible solution:

$re = '/(?<=\(|^)([^()]*)/';  $str = "0a,0b(1a((3a, 3b, 3c)))";  preg_match_all($re, $str, $matches); $res  = array(); foreach ($matches[1] $m){     $res[] = preg_split('/\s*,\s*/',$m); } print_r($res); 

see ideone demo

the regex (?<=\(|^)([^()]*) matches 0 or more characters other ( or ) if preceded ( or start of string.


Comments