不在 () 之间时分解字符串

Explode string when not between ()

我正在尝试 explode 逗号字符串:, 但仅当它不在括号 (...)

之间时

下面是一些代码来说明我的意思:

$string = "K.VisueelNr,IFNULL(P.Partijnaam, 'Leeg gemeld') AS Partijnaam,R.Ras,M.Maat,DATE_FORMAT(KS.Timestamp, '%d-%c-%Y') AS Datum,H.Handelshuis,KS.Actie";

print_r(str_getcsv($string, '()'));

print_r(explode(",", $string));

将输出:

Array
(
    [0] => K.VisueelNr,IFNULL
    [1] => P.Partijnaam, 'Leeg gemeld') AS Partijnaam,R.Ras,M.Maat,DATE_FORMAT
    [2] => KS.Timestamp, '%d-%c-%Y') AS Datum,H.Handelshuis,KS.Actie
)
Array
(
    [0] => K.VisueelNr
    [1] => IFNULL(P.Partijnaam
    [2] =>  'Leeg gemeld') AS Partijnaam
    [3] => R.Ras
    [4] => M.Maat
    [5] => DATE_FORMAT(KS.Timestamp
    [6] =>  '%d-%c-%Y') AS Datum
    [7] => H.Handelshuis
    [8] => KS.Actie
)

但我正在寻找这样的输出:

Array
(
    [0] => K.VisueelNr
    [1] => IFNULL(P.Partijnaam, 'Leeg gemeld') AS Partijnaam
    [2] => R.Ras
    [3] => M.Maat
    [4] => DATE_FORMAT(KS.Timestamp, '%d-%c-%Y') AS Datum
    [5] => H.Handelshuis
    [6] => KS.Actie
)

Here's an PHP Sandbox fiddle to play around

也许必须用 preg_split 完成,但我不知道 regex 会是什么样子...

您需要使用 preg_split 根据给定的正则表达式拆分输入。

$words = preg_split('~,(?![^()]*\))~', $str);
print_r($words);

DEMO

解释:

  • , 匹配所有逗号,只有当它不是
  • 后跟任何字符但不是 (),零次或多次
  • 然后是右括号。

如果将 (?! 更改为 (?=,它与匹配括号内的所有逗号相反。

需要一个适用于嵌套括号的解决方案并想出了这个:

$delimiter = ',';
$string = "K.VisueelNr,IFNULL(P.Partijnaam, 'Leeg gemeld') AS Partijnaam,func(arg1, func(arg2)) as field";

$array = explode($delimiter, $string);
$new_array = [];
$helper_string = '';
$count1 = 0;
$count2 = 0;
foreach ($array as $str) {
    $count1 += substr_count($str, '(');
    $count2 += substr_count($str, ')');
    if (strlen($helper_string) > 0) {
        $helper_string .= $delimiter;
    }
    $helper_string .= $str;
    if ($count1 === $count2) {
        $new_array[] = $helper_string;
        $helper_string = '';
        $count1 = 0;
        $count2 = 0;
    }
}
// Fallback in case of broken brackets
if (strlen($helper_string)) {
    $new_array[] = $helper_string;
}
print_r($new_array);

结果:

Array
(
    [0] => K.VisueelNr
    [1] => IFNULL(P.Partijnaam, 'Leeg gemeld') AS Partijnaam
    [2] => func(arg1, func(arg2)) as field
)