2016-02-06 23:35 阅读 33

preg_match:/ username或/ username / foo

I'm wanting to preg_match the following URIs. Note usernames are: [\w]{1,15}


I want these to fail


The username is mandatory, so the preg_match should work if just a username is given, and then check if anything after is either foo or bar.

preg_match('{^\/([\w]+){1,15}/{/foo|/bar}?$}', $uriString)

You can probably tell my preg_match fails. How may I fix this?

  • 点赞
  • 写回答
  • 关注问题
  • 收藏
  • 复制链接分享

2条回答 默认 最新

  • 已采纳
    dsdsds12222 dsdsds12222 2016-02-06 23:39

    Use parentheses to specify a group of alternatives;

    Curly braces are only used to limit repetition {min,max}

    ^\/\w{1,15}(\/foo|\/bar)?$ ==> DEMO

    Above, we allow \w 1 up to 15 times (\w matches any word character [a-zA-Z0-9_])

    Followed by either \/foo or \/bar

    ^ and $ specify the start and the end of the string, meaning that the regex must match the full string not only a part of it

    You can read more about:

    点赞 评论 复制链接分享
  • dtn51137 dtn51137 2016-02-06 23:59

    You use curly brackets for everything!

    You can't use curly brackets to group, you have to use standard brackets; try this:


    I have replaced your ([\w]+){1,15} with (\w{1,15}): your pattern match also usernames with more than 15 characters, because it search ‘one of more word chars’ repeating 1 to 15 times, but ‘one of more’ match also 16 characters words! Your slash before curly brackets doesn't match 'username' but also 'username/foo' (it match eventually 'username//foo').

    点赞 评论 复制链接分享