Regexp to find the subdomain (if any) from $HTTP_HOST

Collapse
This topic is closed.
X
X
 
  • Time
  • Show
Clear All
new posts
  • Leif Wessman

    Regexp to find the subdomain (if any) from $HTTP_HOST

    I need help creating a regular expression to find the subdomain in the
    $HTTP_HOST variable.

    The domain is always in this form:


    or
    uk.domain.com
    or
    domain.com

    there is no such thing as a
    sub.sub.sub.dom ain.com
    (not in my case, at least)

    So, I need to find out if the subdomain is empty, "www" or "uk".

    Can someone help me?

    Leif
  • Martin C. Petersen

    #2
    Re: Regexp to find the subdomain (if any) from $HTTP_HOST

    > I need help creating a regular expression to find the subdomain in the[color=blue]
    > $HTTP_HOST variable.[/color]
    No need for regular expressions in this case:
    <?php
    $parts = explode(".",$HT TP_HOST);
    $length = count($parts);
    $subdomain = $length>2 ? $parts[$length-3] : "";
    ?>


    Martin


    Comment

    • Shawn Wilson

      #3
      Re: Regexp to find the subdomain (if any) from $HTTP_HOST

      Leif Wessman wrote:[color=blue]
      >
      > I need help creating a regular expression to find the subdomain in the
      > $HTTP_HOST variable.
      >
      > The domain is always in this form:
      >
      > www.domain.com
      > or
      > uk.domain.com
      > or
      > domain.com
      >
      > there is no such thing as a
      > sub.sub.sub.dom ain.com
      > (not in my case, at least)
      >
      > So, I need to find out if the subdomain is empty, "www" or "uk".
      >
      > Can someone help me?
      >
      > Leif[/color]

      Untested:

      $foo = preg_replace("/^(http:\/\/)?([^\.]+)?(\.?domain\. com.*)$", "\$2",
      $HTTP_HOST);
      switch($foo) {
      case "www":
      //statements
      break;
      case "uk":
      //statements
      break;
      case "":
      //statements
      break;
      default:
      echo "Unrecoginz ed URL";
      }
      --
      Shawn Wilson
      shawn@glassgian t.com

      Comment

      Working...