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)
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)
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.
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.
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
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.
The regex /(\([^()]+\))|([^,]+)/
will match everything, except the commas outside parentheses. Does it helps?