I can't get preg_match to test if the entire string matches the regex

后端 未结 2 2015
旧时难觅i
旧时难觅i 2021-01-20 16:43

I\'m using this regular expression to test if a username is valid:

[A-Za-z0-9 _]{3,12} when I test it for matches in a text editor with the string

2条回答
  •  孤城傲影
    2021-01-20 17:19

    You're missing the anchors in the regular expression, so the regex can comfortably match 3 characters in the character class anywhere in the string. This is not what you want. You want to check if your regex matches against the entire string. For that, you need to include the anchors (^ and $).

    if(!preg_match('/^[A-Za-z0-9 _]{3,12}$/', $content)
                     ^                   ^
    

    ^ asserts the position at the beginning of the string and $ asserts position at the end of the string. It's important to note that these meta characters do not actually consume characters. They're zero-width assertions.

    Further reading:

    • Regex Anchors on regular-expressions.info
    • The Stack Overflow Regular Expressions FAQ

提交回复
热议问题