How to split value

I want to share the meaning.

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

I want to break it like this.

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

I used explode ('.', $ Value), but laid out split in brackets. I do not want to separate the value in parentheses. How can i do this?

+3
source share
5 answers

You need a 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
+3
source

explode has a limit parameter:

$array = explode('.', $value, 4);

http://us.php.net/manual/en/function.explode.php

+1
source

- , '.' , ? .

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

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

, :

function split_value($value) {
    $split_values = array();
    $depth = 0;

    foreach (explode('.', $value) as $chunk) {
        if ($depth === 0) {
            $split_values[] = $chunk;
        } else {
            $split_values[count($split_values) - 1] .= '.' . $chunk;
        }

        $depth += substr_count($chunk, '(');
        $depth -= substr_count($chunk, ')');
    }

    return $split_values;
}

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

var_dump(split_value($value));
0

:

$string = "code1.code2.code3.code4(code5.code6(arg1.arg2, arg3), code7.code8)code1.code2.code3.code4(code5.code6(arg1.arg2, arg3), code7.code8)";
$out = array();
$inparen = 0;
$buf = '';
for($i=0; $i<strlen($string); ++$i) {
    if($string[$i] == '(') ++$inparen;
    elseif($string[$i] == ')') --$inparen;

    if($string[$i] == '.' && !$inparen) {
        $out[] = $buf;
        $buf = '';
        continue;
    }
    $buf .= $string[$i];

}
if($buf) $out[] = $buf;
0

Source: https://habr.com/ru/post/1737424/


All Articles