title: Get domain name for any type of URL format? -- PHP to Ruby
body: <p>I have a PHP function which properly extracts the domain name <strong>(without any subdomain)</strong> for any given variation of a url. I'm new to Ruby and having a tough time getting it to work:</p>
  
  <pre><code>function get_domain_name( $url )
  {
      eregi( "http[s]*://([a-zA-Z0-9.-]*)/?.*", $url, $domain );
      $domain = explode( ".", $domain[1] );
  
      if ( strlen( end($domain) ) == 2 &amp;&amp; ( strlen($domain[count($domain)-2]) == 3 || strlen($domain[count($domain)-2]) == 2 )  )
      {
          # special case domains -- ex: co.uk .in .ca
          return strtolower( $domain[count($domain)-3] . "." . $domain[count($domain)-2] . "." . end( $domain ) );
      }
      else
      {
          # regular .com type domains -- three or more letters
          return strtolower( $domain[count($domain)-2] . "." . end( $domain ) );
      }
  }
  </code></pre>
  
  <p>Is there something in Rails that do this same thing already?</p>
  
  <p><strong>UPDATE:</strong></p>
  
  <p><strong>Here's what I ended up going with thanks to @BenW</strong></p>
  
  <pre><code> def extract_domain(url)
      if domain = url.match(/^(http:\/\/)*(www.)*([a-zA-Z0-9.-]*)\/?.*/i)
        domain = domain[3].split('.')
        if (domain.last.length == 2) &amp;&amp; (domain[-2].length == 3 || domain[-2].length == 2)
          # special case domains -- ex: co.uk .in .ca
          domain[-3..-1].join('.')
        else
          # regular .com type domains -- three or more letters
          domain[-2..-1].join('.')
        end
      end
    end
  </code></pre>
  
  <p>It accepts all these formats:</p>
  
  <pre><code>http://www2.google.com
  www2.google.com
  http://www.google.com
  http://www.google.co.uk
  www.google.com
  google.co.uk
  http://some.long.ass.subdomain.google.com
  </code></pre>