PHP Regular Expression to match `name[50]` to the "name" and "50" values
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 kn开发者_运维百科owledge! /([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
精彩评论