正则表达式中逗号后的可选匹配项

I tried so hard and got so far but in the end it doesn't work!!

What I would like to do achieve is the following: I've got a preg_replace_callback function where I want to address my "dictionary" function.

I use my own "dictionary" tag:

<[general,username]>
<[general,username,1]>

this should call my function "dictionary". The function with it's ararguments is: dictionary($search,$section,$upper=null)

$search = filename
$section = array key
$upper = (int) 1 to 3

my callback function calls the function with the values from the "dictionary" tags.

for <[general,username]> I need
- $search = general
- $section = username
- $upper = null

but for <[general,username,1]> I want
- $search = general
- $section = username
- $upper = 1

I want my regular expression to always match 2 arguments (search and section) but have a third optional argument.

My regex:

/\<\[([^\[]+)\,([^\[]+)(\,[0-2])?\]\>/

but this doesn't work correctly. I get the following results:

for <[general,username]> I get

[0] => <[general,username]>
[1] => general
[2] => username

for <[general,username,1]> I get

[0] => <[general,username,1]>
[1] => general,username
[2] => 1

but I would like

[0] => <[general,username,1]>
[1] => general
[2] => username
[3] => 1

What am I doing wrong??

Try this out:

/\<\[([^\,]+)\,([^\,]+)(?:\,(\d+))?\]\>/
 - Item[0] => whole matching text
 - Item[1] => general
 - Item[2] => username
 - Item[3] => upper (if match)

The regex is greedy by default, so the first group is matching the first comma as well. Try this instead:

/\<\[([^\[,]+)\,([^\[,]+)(?:\,([0-2]))?\]\>/

Exclude the comma from the range of the second group....

Or, assuming the first 2 terms are alphanumeric only:

\<\[(\w+)\,(\w+)\,?(\d+)?\]\>