StackTips

Get Domain Name from URL in PHP Using Regular Expressions

stacktips avtar

Written by

Editorial,  1 min read,  2.78K views, updated on Sept. 17, 2023

The following PHP code snippet extracts the domain name from long URL using regular expressions. For example, if you pass the following url, it will output stacktips.com.

http://stacktips.com/articles/drupal-vs-wordpress-which-one-to-choose

Snippet:

//Custom method to get domain name from url
function get_domain_from_url($url)
{
  $pieces = parse_url($url);
  $domain = isset($pieces['host']) ? $pieces['host'] : '';
  if (preg_match('/(?P<domain>[a-z0-9][a-z0-9\-]{1,63}\.[a-z\.]{2,6})$/i', $domain, $regs)) {
    return $regs['domain'];
  }
  return '';
}

stacktips avtar

Editorial

StackTips provides programming tutorials, how-to guides and code snippets on different programming languages.

Related posts

Let’s be friends!

🙌 Stay connected with us on social media for the latest updates, exclusive content, and more. Follow us now and be part of the conversation!