PHP regex to match alphanumeric and hyphens (not spaces) for use as subdomain

前端 未结 1 1558
伪装坚强ぢ
伪装坚强ぢ 2021-01-23 02:20

I have the following regex, which I interpret as a pattern that will match a string consisting of just alphanumeric characters and hyphens.

if (preg_match(\'/[A         


        
相关标签:
1条回答
  • 2021-01-23 02:41

    Your pattern matches an ASCII letter or digit or - anywhere inside a string, and if found, returns true. E.g., it will return true if you pass $#$%$&^$g to it.

    A pattern that will match a string consisting of just alphanumeric characters and hyphens is

    if (preg_match('/^[A-Za-z0-9-]+$/D', $subdomain)) {
        // valid subdomain
    }
    

    Details:

    • ^ - start of string
    • [A-Za-z0-9-]+ - 1 or more chars that are either ASCII letters, digits or -
    • $ - end of string
    • /D - a PCRE_DOLLAR_ENDONLY modifier that makes the $ anchor match at the very end of the string (excluding the position before the final newline in the string).
    0 讨论(0)
提交回复
热议问题