dsf1222 2013-08-12 03:06
浏览 19
已采纳

允许特定用户名的PHP正则表达式[关闭]

This is my first question here. Currently I'm developing a PHP forum script and I want to let people register a username abiding by my rules.

The rules are simple:

  • First character must be a letter
  • They can also use numbers but it isn't the first
  • They can use fullstop/underscore once but not at the end of a username

Please help me by putting down a function. I read some tutorial but don't understand regular expressions well. And for this reason I'm stuck. Thanks in advance for your answer.

Added after 20 min:

Thanks for answering, I have one more thing to ask, Can I detarmine dumb usernames?? E.G. aaa123, ab-cd,uuuu...Than How?

  • 写回答

4条回答 默认 最新

  • douya2006 2013-08-12 03:11
    关注

    Take the parts you describe:

    • First character must be a letter

    It starts ^[A-Za-z]

    • They can also use numbers but it isn't the first

    [A-Za-z0-9]* in the middle

    • They can use fullstop/underscore once but not at the end of a username

    Optionally, have an underscore followed by at least one of the other valid characters ([._][A-Za-z]+)?

    Put it all together and you have: /^[A-Za-z][A-Za-z0-9]*([._][A-Za-z0-9]+)?$/. Using the case '/i' insensitive flag lets you drop the 'A-Z': /^[a-z][a-z0-9]*([._][a-z0-9]+)?$/i.

    Regular expressions are equivalent to deterministic finite automatons (DFA). Studying them can help get a grasp on regular expressions. In particular, transitioning between states is directly applicable to your three points. The (reduced) state diagram for this language should be quite easy to understand: State diagram for /^[a-z][a-z0-9]*([._][a-z0-9])?/

    The DFA:

    • starts in state 0
    • transitions to state 1 if a letter is encountered,
    • stays in state 1 as long as letters and digits are encountered,
    • switches to state 2 if a period or underscore are encountered,
    • switches to state 3 if a letters and digit is encountered,
    • stays in state 3 as long as letters and digits are encountered,
    • accepts the string if it ends in state 1 or 3

    I call it "reduced" because there's a fifth, non-accepting state and edges leading to it that aren't shown. Basically, if a character is encountered other than one listed, the DFA transitions to the fifth, non-accepting state and stays there.

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(3条)

报告相同问题?

悬赏问题

  • ¥15 stm32开发clion时遇到的编译问题
  • ¥15 lna设计 源简并电感型共源放大器
  • ¥15 如何用Labview在myRIO上做LCD显示?(语言-开发语言)
  • ¥15 Vue3地图和异步函数使用
  • ¥15 C++ yoloV5改写遇到的问题
  • ¥20 win11修改中文用户名路径
  • ¥15 win2012磁盘空间不足,c盘正常,d盘无法写入
  • ¥15 用土力学知识进行土坡稳定性分析与挡土墙设计
  • ¥70 PlayWright在Java上连接CDP关联本地Chrome启动失败,貌似是Windows端口转发问题
  • ¥15 帮我写一个c++工程