开发者

Preg_split by comma, ignore parentheses, PHP

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, stri开发者_如何学运维ng3";

result should be:

array(
   [0] => string1 (sString1, sString2,(ssString1, ssString2))
   [1] => string2
   [2] => string3
)


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.


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

?>
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜