The question is: How to do this using only (and a single) regex? Is it possible?
Explanation: I have an array like this:
array
(
[0] => 'code1-{1,5}{a,c}',
[1] => 'code2-{3,6}{s,q}'
)
and what I want to do is to get, using a regex, all the values grouped like:
code1
1,5
a,c
I know that I can get all the data inside the {...} using this regex:
'/\{([^\}]*)\}/i'
Besides I know that I can get the string before the dash using this one
/(.*?)\-/i
What I don’t know is if it’s possible to merge this two regex. Infact, if I have this regex
'/(.*?)\-\{([^\}]*)\}/i'
I can’t get all the data I need. I also know that I can do something like this:
'/(.*?)\-\{([^\}]*)\}\{([^\}]*)\}/i'
but if the format of the input will change to say 10 {…} groups, it’s no so elegant to have 10 group of the form \{([^\}]*)\} and it’s not the point of my question.
Here are the code that I’m trying:
First regex('/\{([^\}]*)\}/i'): http://ideone.com/mN3T2
Merged regex('/(.*?)\-\{([^\}]*)\}/i'): http://ideone.com/gMdOa
Update: After OP’s edit
I don’t believe you can merge those two regular expressions and still retain the ability to loop through the matches of the form
{1,5}. I think it is better to use two separate regular expressions for this purpose, one to capturecodenand another to iterate over matches of text between{}.One way to do this is to split over
-like this$result = preg_split('/-/m', 'code1-{1,5}{a,c}');and then you get
code1as the first entry and{1,5}{a,c}as the second entry. Now apply your regex\{([^\}]*)\}over the second entry and iterate over the matches.