2

i've problem by using the preg_split method. I wanna split by comma but only if the comma isn't between ( and ).

For example:

id,user(id,firstname),image(id)

Should return:

0 => id
1 => user(id,firstname)
2 => image(id)
NotMe
  • 87,343
  • 27
  • 171
  • 245
MrBoolean
  • 601
  • 7
  • 13
  • you should have enclosures, what's the source of the data? bad CSV form at a guess –  Sep 24 '12 at 21:49
  • 4
    You should do `_match`ing, not splitting. – mario Sep 24 '12 at 21:50
  • 1
    possible duplicate of [Explode complex string by commas in PHP](http://stackoverflow.com/questions/11062241/explode-complex-string-by-commas-in-php) (Just picked the first google link, there are others ...) – mario Sep 24 '12 at 21:51

5 Answers5

2

Quick and readable solution might be this:

<?php
function parse($str) {
    $str = preg_replace('~(\(.*?),(.*?\))~', '$1_#_PLACEHOLDER_#_$2', $str);

    $items = array();
    foreach (explode(',', $str) as $item) {
        $items[] = str_replace('_#_PLACEHOLDER_#_', ',', $item);
    };
    return $items;
}

var_dump(parse('id,user(id,firstname),image(id)'));

It could definitely be done with a single regex, but readability would be severely hurt.

Mikulas Dite
  • 7,790
  • 9
  • 59
  • 99
0

You may want to try a parser-generator rather than a regex. I'm not familiar with the alternatives in PHP, but this answer indicates a couple alternatives.

Community
  • 1
  • 1
Stig Brautaset
  • 2,602
  • 1
  • 22
  • 39
0

I would suggest trying to find a parser instead, but it can be done using regular expressions.

Use the following regular expression: /\G(?> *)(?|([^,]*\((?>\\.|[^()])+\)[^,]*)|(?![()])([^,]+?)) *(?:,|$)/g

More details here: http://regex101.com/r/nA7dW5

Good luck

Firas Dib
  • 2,743
  • 19
  • 38
0

I have solved this issue using preg_split with PREG_SPLIT_DELIM_CAPTURE.

$tokens = preg_split('#(\,|\(|\))#', 'id,user(id,firstname),image(id)', PREG_SPLIT_DELIM_CAPTURE);

Returns:

["id", ",", "user", "(", "id", "firstname", ")", "image", "(", "id", ")"]

After that you can parse that array with a simple switch case.

MrBoolean
  • 601
  • 7
  • 13
-1

The regex /(\([^()]+\))|([^,]+)/ will match everything, except the commas outside parentheses. Does it helps?

  • 1
    No, you can't, given that that is for javascript. Not php; it's a different flavor of regex, not everything is the same. Use http://www.spaweditor.com/scripts/regex/index.php instead. – Daedalus Sep 24 '12 at 22:00
  • And as it stands, the above regex doesn't meet the OP's requirements. – Daedalus Sep 24 '12 at 22:03
  • You can use www.regex101.com to test your regular expression. It uses PHP. Full version details in the "about" tab. Also, my answer should work for OP. – Firas Dib Sep 25 '12 at 09:24