Note that there are some explanatory texts on larger screens.

plurals
  1. POPHP: split string on comma, but NOT when between braces or quotes?
    primarykey
    data
    text
    <p>In PHP I have the following string :</p> <pre><code>$str = "AAA, BBB, (CCC,DDD), 'EEE', 'FFF,GGG', ('HHH','III'), (('JJJ','KKK'), LLL, (MMM,NNN)) , OOO"; </code></pre> <p>I need to split this string into the following parts:</p> <pre><code>AAA BBB (CCC,DDD) 'EEE' 'FFF,GGG' ('HHH','III') (('JJJ','KKK'),LLL, (MMM,NNN)) OOO </code></pre> <p>I tried several regexes, but couldn't find a solution. Any ideas?</p> <p><strong>UPDATE</strong></p> <p>I've decided using regex is not really the best solution, when dealing with malformed data, escaped quotes, etc.</p> <p>Thanks to suggestions made on here, I found a function that uses parsing, which I rewrote to suit my needs. It can handle different kind of brackets and the separator and quote are parameters as well.</p> <pre><code> function explode_brackets($str, $separator=",", $leftbracket="(", $rightbracket=")", $quote="'", $ignore_escaped_quotes=true ) { $buffer = ''; $stack = array(); $depth = 0; $betweenquotes = false; $len = strlen($str); for ($i=0; $i&lt;$len; $i++) { $previouschar = $char; $char = $str[$i]; switch ($char) { case $separator: if (!$betweenquotes) { if (!$depth) { if ($buffer !== '') { $stack[] = $buffer; $buffer = ''; } continue 2; } } break; case $quote: if ($ignore_escaped_quotes) { if ($previouschar!="\\") { $betweenquotes = !$betweenquotes; } } else { $betweenquotes = !$betweenquotes; } break; case $leftbracket: if (!$betweenquotes) { $depth++; } break; case $rightbracket: if (!$betweenquotes) { if ($depth) { $depth--; } else { $stack[] = $buffer.$char; $buffer = ''; continue 2; } } break; } $buffer .= $char; } if ($buffer !== '') { $stack[] = $buffer; } return $stack; } </code></pre>
    singulars
    1. This table or related slice is empty.
    plurals
    1. This table or related slice is empty.
 

Querying!

 
Guidance

SQuiL has stopped working due to an internal error.

If you are curious you may find further information in the browser console, which is accessible through the devtools (F12).

Reload