Tutorials PHP Get Domain Name from URL in PHP Using Regular Expressions

Get Domain Name from URL in PHP Using Regular Expressions

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/reviews/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 '';
}

Total
0
Shares
guest
0 Comments
Inline Feedbacks
View all comments
Previous Post
Wordpress Tutorials

Limit Archive Page Content with Read More Link in WordPress

Next Post

How to Extract Twitter Username from Url

Related Posts
By clicking “Allow All”, you agree to the storing of cookies on your device to enhance site navigation, analyze site usage, and assist in our marketing efforts. Cookie Notice
Allow All
0
Would love your thoughts, please comment.x
()
x