Regexp split by comma, not within brackets

Posted on 2005-05-03
Last Modified: 2006-11-18
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)
(Test9, Test10)
Test 11

Can anyone help? ... Please ...
Question by:mcuk_storm
    LVL 9

    Accepted Solution

    Don't think it's possible using a single regexp. Try this though:


    $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] == '(') {
        else if ($str[$i] == ')') {
      array_push($op, substr($str, $start, $i-$start));
      return $op;

    LVL 7

    Author Comment

    Was hoping for a regexp, but at least there is a good reason for me struglling ;)  Thanks for the alternate solution keteracel.

    Featured Post

    Maximize Your Threat Intelligence Reporting

    Reporting is one of the most important and least talked about aspects of a world-class threat intelligence program. Here’s how to do it right.

    Join & Write a Comment

    Introduction Many web sites contain image galleries; a common design for these galleries includes a page with a collection of thumbnail images.  You can click on each of the thumbnail images to see the larger version of the image.  This is easily i…
    These days socially coordinated efforts have turned into a critical requirement for enterprises.
    Learn how to match and substitute tagged data using PHP regular expressions. Demonstrated on Windows 7, but also applies to other operating systems. Demonstrated technique applies to PHP (all versions) and Firefox, but very similar techniques will w…
    The viewer will learn how to create and use a small PHP class to apply a watermark to an image. This video shows the viewer the setup for the PHP watermark as well as important coding language. Continue to Part 2 to learn the core code used in creat…

    734 members asked questions and received personalized solutions in the past 7 days.

    Join the community of 500,000 technology professionals and ask your questions.

    Join & Ask a Question

    Need Help in Real-Time?

    Connect with top rated Experts

    19 Experts available now in Live!

    Get 1:1 Help Now