2010-03-17 76 views
3

我想拆分值。如何拆分值

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

我使用了爆炸('。',$ value),但爆炸分解为括号内的值。我不想在括号中分割值。 我该怎么办?

+0

你刨去打破'码4​​(code5.code6(ARG1。 arg2,arg3),code7.code8)'下一部分EP?即无论如何你想写一个或多或少完整的解析器? – VolkerK 2010-03-17 21:22:52

+0

@VolkerK我想简单的解析器。只有一行解析。 – 2010-03-17 21:27:22

+0

'(arg1.arg2,arg3)'不应该是'(arg1,arg2,arg3)'?还有这个'code *'的东西。他们是否会有相同的名字,可能会附带不同的数字(如您的示例中)还是它是随意的?如果这一切都是这样,我有一个工作解决方案......但我只是不确定。 – 2010-03-17 21:43:03

回答

3

你需要preg_match_all和递归正则表达式来处理嵌套遗传

$ 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 
+0

+1尼斯-------- – 2010-03-17 21:56:39

+0

这并不完全符合他所寻找的输出。签出“code4”。 – 2010-03-17 22:00:04

+0

*〜*〜* Mind.blown。*〜*〜* – notJim 2010-03-17 22:01:20

0

您能否使用'。'以外的内容。分离你想分裂的代码?否则,你需要一个正则表达式替换。

$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

我必须使用点(。) – 2010-03-17 21:14:34

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;