I can't think of a way to do this using one regex, but it's pretty easy to hack something that works:
function process($data) { $entries = array(); $filteredData = $data; if (preg_match_all("/\(([^)]*)\)/", $data, $matches)) { $entries = $matches[0]; $filteredData = preg_replace("/\(([^)]*)\)/", "-placeholder-", $data); } $arr = array_map("trim", explode(",", $filteredData)); if (!$entries) { return $arr; } $j = 0; foreach ($arr as $i => $entry) { if ($entry != "-placeholder-") { continue; } $arr[$i] = $entries[$j]; $j++; } return $arr; }
If you call it like this:
$data = "one, two, three, (four, five, six), seven, (eight, nine)"; print_r(process($data));
It outputs:
Array ( [0] => one [1] => two [2] => three [3] => (four, five, six) [4] => seven [5] => (eight, nine) )
Emil h
source share