Nahydrin
Nahydrin

Reputation: 13507

Regex optional non-regex group match

Say I have the following, as input:

Tonic,Love,(Original,Mix),house,dance,ton!c

Here are the rules I am trying to get:

  1. All commas seperate an individual keyword, except when #2 is true.
  2. Commas have no effect between round brackets.
    • All round brackets group keywords as one keyword.

I have the following regex right now:

#([\(?.*?\)])|(.*?),#

I end up with results like this:

Tonic
Love
(Original
Mix)
house
dance

It's the same as splitting by the comma, except I have lost the last keyword ton!c. I do not require this to all happen in one regex, but it is preferred.

Upvotes: 1

Views: 124

Answers (3)

heinrich5991
heinrich5991

Reputation: 2983

Try

"(\([^)]+\))|([^(][^,]*)(,(\([^)]+\))|([^(][^,]*))*"

This catches all groups at once.

Upvotes: 0

Qtax
Qtax

Reputation: 33908

You could split on:

/,(?![^(]*\))/

or match all with:

/\([^)]*\)|[^,()]*/

at least for your examples.

I.e:

$array = preg_split('/,(?![^(]*\))/', $string);

Upvotes: 1

Guillaume Poussel
Guillaume Poussel

Reputation: 9822

This simple one : \([^\)]*\)|[^,]* should work.

Upvotes: 2

Related Questions