PHP正则表达式将`name [50]`与“name”和“50”值匹配

I'm looking for some more regular expression help, to work with the PHP function preg_match. I need to match the following strings;

  • string[50]
  • string

Ideally the array returned would be something like this;

  • string, 50
  • string

Any help would be appreciated :-) This was what I came up with but it doesn't remotely do what I expected with my little regex knowledge! /([a-z])+(\[[0-9]\])?/i

You need to put the + within the () (otherwise you'll match the full string only the last character of the string will be in the result group). Also add another + after [0-9]. Move the \[\] outside the () to return only 50 (not [50]) and use (?:)? to make the [50] optional without yielding a group.

/([a-z]+)(?:\[([0-9]+)\])?/i

Play with it on rubular