Learn how to a build a cloud-first strategyRegister Now

x
  • Status: Solved
  • Priority: Medium
  • Security: Public
  • Views: 872
  • Last Modified:

Regexp split by comma, not within brackets

Hi, I am struggling to write a regular expression to split a string by comma's but only commas that are not enclosed within brackets, these brackets could also be nested e.g.

Test1 (Test2, Test3, (Test4, Test5), Test6), Test7, Test8, (Test9, Test10), Test 11
should be split into
Test1 (Test2, Test3, (Test4, Test5), Test6)
Test7
Test8
(Test9, Test10)
Test 11

Can anyone help? ... Please ...
0
mcuk_storm
Asked:
mcuk_storm
1 Solution
 
keteracelCommented:
Don't think it's possible using a single regexp. Try this though:

<?php

$str = "Test1 (Test2, Test3, (Test4, Test5), Test6), Test7, Test8, (Test9, Test10), Test 11";

function splitString($str) {
  $op = array();
  $start = 0;
  $openBrackets = 0;

  for ($i = 0; $i < strlen($str); $i++) {
    if ($str[$i] == ',' && $openBrackets == 0) {
      array_push($op, substr($str, $start, $i-$start));
      $start = $i + 1;
    }
    else if ($str[$i] == '(') {
      $openBrackets++;
    }
    else if ($str[$i] == ')') {
      $openBrackets--;
    }
  }
  array_push($op, substr($str, $start, $i-$start));
  return $op;
}

print_r(splitString($str));
?>
0
 
mcuk_stormAuthor Commented:
Was hoping for a regexp, but at least there is a good reason for me struglling ;)  Thanks for the alternate solution keteracel.
0

Featured Post

Hire Technology Freelancers with Gigs

Work with freelancers specializing in everything from database administration to programming, who have proven themselves as experts in their field. Hire the best, collaborate easily, pay securely, and get projects done right.

Tackle projects and never again get stuck behind a technical roadblock.
Join Now