Skip to main content

Extracts the domain name from a URL. http://www.jonlabelle.com => jonlabelle.com.

/**
   * Get domain name from URL
   *
   * Check whether each part of the domain is not longer than 63 characters,
   * and allow internationalized domain names using the punycode notation.
   *
   * @param  string  $url
   * @param  boolean $remove_www Remove the "www" prefix. The default is true.
   * @return string
   */
  function get_domain_name($url, $remove_www = true) {
    if (preg_match('/\b((?=[a-z0-9-]{1,63}\.)(xn--)?[a-z0-9]+(-[a-z0-9]+)*\.)+[a-z]{2,63}\b/', $url, $matches)) {
      return $remove_www ? preg_replace('/www\./i', '', $matches[0]) : $matches[0];
    } else {
      return "";
    }
  }