phpsplitparentheses

Split on dots not inside parentheses


I want to split value.

$value = "code1.code2.code3.code4(code5.code6(arg1.arg2, arg3), code7.code8)";

I want to split like this.

Array
(
    [0] => code1
    [1] => code2
    [2] => code3
    [3] => code4(code5.code6(arg1.arg2, arg3), code7.code8)
)

I used explode('.', $value), but explode splits in parentheses value too. I don't want to split inside parenthetical expressions. How can I do?


Solution

  • You need preg_match_all and a recursive regular expression to handle nested parethesis

    $re = '~( [^.()]* ( ( ( [^()]+ | (?2) )* ) ) ) | ( [^.()]+ )~x';

      $re = '~( [^.()]* ( \( ( [^()]+ | (?2) )* \) ) ) | ( [^.()]+ )~x';
    

    test

     $value = "code1.code2.code3.code4(code5.code6(arg1.arg2, arg3), code7.code8).xx.yy(more.and(more.and)more).zz";
    
     preg_match_all($re, $value, $m, PREG_PATTERN_ORDER);
     print_r($m[0]);
    

    result

    [0] => code1
    [1] => code2
    [2] => code3
    [3] => code4(code5.code6(arg1.arg2, arg3), code7.code8)
    [4] => xx
    [5] => yy(more.and(more.and)more)
    [6] => zz