Regular expression for comma matching not between grouping characters

I need a regular expression that will match a comma that is NOT between "[" and "]" or "(" and ")" or "{" and "}". Other grouping characters do not matter. I tried to figure it out, but I can't think of anything to do it.

The regular expression should be used with the PHP preg_split function to split the string into matching commas.

An example of a string containing commas and grouping characters:

<div>Hello<div>,@func[opt1,opt2],{,test},blahblah

The line should be divided as follows:

1: '<div>Hello<div>'
2: '@func[opt1,opt2]'
3: '{,test}'
4: 'blahblah'

And I just thought about it, but at this point all the grouping symbols are guaranteed to have the corresponding symbols, if that helps.

Any help would be BIG appriciated =)

+5
2

. :

$str = '<div>Hello<div>,(foo,bar),@func[opt1,opt2],{,test},blahblah';
$arr = preg_split('~([^,]*(?:{[^}]*}|\([^)]*\)|\[[^]]*])[^,]*)+|,~', $str, -1 , PREG_SPLIT_DELIM_CAPTURE | PREG_SPLIT_NO_EMPTY);
var_dump($arr);

:

array(5) {
  [0]=>
  string(15) "<div>Hello<div>"
  [1]=>
  string(9) "(foo,bar)"
  [2]=>
  string(16) "@func[opt1,opt2]"
  [3]=>
  string(7) "{,test}"
  [4]=>
  string(8) "blahblah"
}
+10

, . , ( [({, a])}), , RE .

+1

All Articles