Explode string if not between ()
I am trying to explode
create a line with a comma: ,
but only if it is not between the brackets(...)
Here's some code to show what I mean:
$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));
The output will be:
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
)
But I'm looking for an output like this:
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 a PHP Sandbox script to play around
It might need to be done with preg_split , but I don't know what it looks like regex
then ...
source to share
You need to use preg_split
one that splits the input according to a given regular expression.
$words = preg_split('~,(?![^()]*\))~', $str);
print_r($words);
Explanation:
-
,
matches all commas only if it is not - followed by any char, but not
(
or)
, zero or more times - followed by a closing parenthesis.
If you change (?!
to (?=
, it does the opposite match for all the commas that are present inside the parentheses.
source to share