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

心不动则不痛 提交于 2020-01-04 16:56:10

问题


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


来源:https://stackoverflow.com/questions/42558881/php-regex-to-match-alphanumeric-and-hyphens-not-spaces-for-use-as-subdomain

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!