PHP regex to match alphanumeric and hyphens (not s

2019-07-19 11:38发布

问题:

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-Za-z0-9-]/', $subdomain) === false) {
    // valid subdomain
}

The problem is this regex is also matching blank spaces, which is obviously undesirable in a subdomain name.

For bonus points, is this a suitable way to validate subdomain names? I'm unsure which special characters are allowed but thought I would keep it simple by only allowing hyphens. Is there anything else I need to check for? For instance a maximum length?

回答1:

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).