Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Explode string when not between ()

I'm trying to explode an string by comma's: , but only when it's not between parenthesis (...)

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

Which will output:

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 an PHP Sandbox fiddle to play around

Maybe it has to be done with preg_split, but I don't know how the regex would look like then...

like image 311
Mathlight Avatar asked Jun 25 '15 05:06

Mathlight


People also ask

How do you explode a string?

The explode() function breaks a string into an array. Note: The "separator" parameter cannot be an empty string. Note: This function is binary-safe.

What does the explode () function do?

The explode function is utilized to "Split a string into pieces of elements to form an array". The explode function in PHP enables us to break a string into smaller content with a break. This break is known as the delimiter.

How can I split a string into two parts in PHP?

PHP | explode() Function explode() is a built in function in PHP used to split a string in different strings. The explode() function splits a string based on a string delimiter, i.e. it splits the string wherever the delimiter character occurs.

What are the parameters for explode?

The explode() function takes three parameters one optional and two mandatory. This parameter specifies the number of elements in the array. This parameter can be +,- or 0. If set positive: The array is returned will contain a maximum of limit elements.


1 Answers

You need to use preg_split which splits the input according to the given regex.

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

DEMO

Explanation:

  • , matches all the commas, only if it's not
  • followed by any char but not of ( or ), zero or more times
  • and further followed by a closing bracket.

If you change (?! to (?=, it does the opposite of matching all the commas which are present inside the brackets.

like image 75
Avinash Raj Avatar answered Oct 16 '22 23:10

Avinash Raj