Regex help: subdomain check

2019-08-15 10:59发布

Hey I have a form where the person enters the subdomain like value.google.com and the entry would be "valid"

I want to run a regex check (I am absolutely horrible at regex) that does the following:

First Character: Cannot be symbol Middle Characters: a-z, A-Z, and symbols - and . ONLY Last character: Cannot be a symbol

I want it to spit out false if it fails the test.

Can anyone help me out with this? Thanks!

Also any other limitations do you guys think should be in there?

3条回答
爷、活的狠高调
2楼-- · 2019-08-15 11:39

If the TLD is always com you should be able to do with:

/^(.*)\.[^.]+\.com$/

This will match whatever's before the rightmost . character (excluding the .com).

However, you might want to do this with simple string operations instead (strrpos()). Or, you could split on .:

function extract_sub($domain) {
        $parts = explode('.', $domain);

        return implode('.', array_slice($parts, 0, -2));
}

(Demo)

查看更多
对你真心纯属浪费
3楼-- · 2019-08-15 11:40

I think this is probably the most common situation.

$subdomain = "usersubdomain";

if(preg_match("/^[A-Z0-9]+$/i", $subdomain)) {
   echo "Valid sub domain";
  }else{
   echo "Not a valid sub domain.";
  }
查看更多
叼着烟拽天下
4楼-- · 2019-08-15 11:47

What you need is a character class. :)

  • [a-zA-Z\-\.] would match characters of type "a-zA-Z-.".
  • [a-zA-Z] would match characters of type "a-zA-Z".
  • ^ means beginning of line
  • $ means end of line
  • + means "one or more times"

So what you are looking for is: ^[a-zA-Z][a-zA-Z\-\.]+[a-zA-Z]$

And since you in PHP can set i-flag it becomes case insensitive and this code should work:


  if (preg_match("/^[a-z][a-z\-\.]+[a-z]$/i", "valid.google.com")) {
   echo "A match was found.";
  } else {
   echo "A match was not found.";
  }

Tip: Should you not also include numbers? [a-z0-9]

查看更多
登录 后发表回答