PHP regexp for /prefix/action(/id)
I'm trying to build a regexp that would match both strings:
/prefix/action
and
/prefix/action/43
but not
/prefix/action/
or
/prefix/action43
where 43 can be anything like [0-9]+, only if preceded by a slash
I also want to capture the number (not the slash), if any, as a named group.
~/prefix/action/?(?P<itemID&开发者_开发知识库gt;[0-9]+)?~
This expression does match, except for a condition that numbers must be preceded by a slash, all my attempts at adding lookahead or lookbehind assertions failed on this one.
I do understand that with additional external processing the task can be solved, but I'm looking for a regexp solution only. Thank you for understanding.
Your suggestions are greatly appreciated.
Solved by:
~/prefix/action(?:/(?P<itemID>[0-9]+))?~
How about making both the /
and the following number optional?
^/prefix/action(?:/[0-9]+)?$
To capture the optional number in a named group add (?P<itemID>...)
around the number regex:
^/prefix/action(?:/(?P<itemID>[0-9]+))?$
Also note that I've added start and end anchors, which were missing in your regex. Without them you'll get a match if you have a sub-string of the input that matches the regex.
精彩评论