2

I have to split a string and I want to avoid splitting it with commas inside parentheses. So how can I implement that?

Example:

$string = "string1 (sString1, sString2,(ssString1, ssString2)), string2, string3";

result should be:

array(
   [0] => string1 (sString1, sString2,(ssString1, ssString2))
   [1] => string2
   [2] => string3
)
PPPHP
  • 747
  • 10
  • 20
  • 1
    This is not a job for a Regular Expression, since this expression is not regular. Compare with [this epic](http://stackoverflow.com/questions/1732348/regex-match-open-tags-except-xhtml-self-contained-tags/1732454#1732454), same thing. :) – deceze Dec 27 '10 at 10:39

2 Answers2

7

You're going to get in an awful mess trying to do this with regex. It's very simple to loop through the characters of a string and do this kind of checking. Something like the following should work:

<?php

function specialsplit($string) {
    $level = 0;       // number of nested sets of brackets
    $ret = array(''); // array to return
    $cur = 0;         // current index in the array to return, for convenience

    for ($i = 0; $i < strlen($string); $i++) {
        switch ($string[$i]) {
            case '(':
                $level++;
                $ret[$cur] .= '(';
                break;
            case ')':
                $level--;
                $ret[$cur] .= ')';
                break;
            case ',':
                if ($level == 0) {
                    $cur++;
                    $ret[$cur] = '';
                    break;
                }
                // else fallthrough
            default:
                $ret[$cur] .= $string[$i];
        }
    }

    return $ret;
}

var_export(specialsplit("string1 (sString1, sString2,(ssString1, ssString2)), string2, string3"));

/*array (
  0 => 'string1 (sString1, sString2,(ssString1, ssString2))',
  1 => ' string2',
  2 => ' string3',
)*/

Note that this technique is a lot harder to do if you have more than a one-character string to split on.

lonesomeday
  • 233,373
  • 50
  • 316
  • 318
  • i try to do it with preg_split and spent more than 2 hours, but it is not working.... Really big thank you for that code :) – Ahmed Bermawy Apr 06 '18 at 15:46
0

I tried my best... it may works for you..

<?php
$string = "string1 (sString1, sString2,(ssString1, ssString2)), string2, string3";
$pattern = '#(?<=\)),#';
$out=preg_split($pattern,$string);
$more=split(",",array_pop($out));
$res=array_merge($out,$more);
echo "<pre>";
print_r($res);

?>
xkeshav
  • 53,360
  • 44
  • 177
  • 245