代码之家  ›  专栏  ›  技术社区  ›  Can Aydoğan

如何分割价值

  •  3
  • Can Aydoğan  · 技术社区  · 14 年前

    我想分割价值。

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

    我想这样分开。

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

    我使用了explode('.',$value),但在括号值中使用了explode split。我不想在括号中拆分值。 我该怎么办?

    5 回复  |  直到 14 年前
        1
  •  3
  •   user187291    14 年前

    你需要preg_match_all和一个递归正则表达式来处理嵌套的parethesis

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

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

    测试

     $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]);
    

    结果

    [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
    
        2
  •  1
  •   webbiedave    14 年前

    explode有一个限制参数:

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

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

        3
  •  0
  •   Matthew Vines    14 年前

    你能用“.”以外的东西来分隔你想拆分的代码吗?否则,需要替换regex。

    $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)
    )
    
        4
  •  0
  •   Ross Snyder    14 年前

    我想这行得通:

    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));
    
        5
  •  0
  •   Rob    14 年前

    一个简单的解析器:

    $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;