我正在尝试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
会是什么样子......
答案 0 :(得分:4)
您需要使用preg_split
根据给定的正则表达式分割输入。
$words = preg_split('~,(?![^()]*\))~', $str);
print_r($words);
说明:
,
匹配所有逗号,只有它不是(
或)
,零次或多次如果您将(?!
更改为(?=
,则会与匹配括号内的所有逗号相反。
答案 1 :(得分:0)
需要一种适用于嵌套括号的解决方案,并提出以下解决方案:
$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
)