Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Extract top domain from string php

Tags:

string

php

I need to extract the domain name out of a string which could be anything. Such as:

$sitelink="http://www.somewebsite.com/product/3749875/info/overview.html";

or

$sitelink="http://subdomain.somewebsite.com/blah/blah/whatever.php";

In any case, I'm looking to extract the 'somewebsite.com' portion (which could be anything), and discard the rest.

like image 455
nooblag Avatar asked Feb 07 '13 07:02

nooblag


2 Answers

With parse_url($url)

<?php
$url = 'http://username:password@hostname/path?arg=value#anchor';

print_r(parse_url($url));
?>

The above example will output:

Array
(
    [scheme] => http
    [host] => hostname
    [user] => username
    [pass] => password
    [path] => /path
    [query] => arg=value
    [fragment] => anchor
)

Using thos values

echo parse_url($url, PHP_URL_HOST); //hostname

or

$url_info = parse_url($url);
echo $url_info['host'];//hostname
like image 111
2 revs Avatar answered Oct 06 '22 23:10

2 revs


2 complexe url

$url="https://www.example.co.uk/page/section/younameit";
or
$url="https://example.co.uk/page/section/younameit";

To get "www.example.co.uk":

$host=parse_url($url, PHP_URL_HOST);

To get "example.co.uk" only

$parts = explode('www.',$host);
$domain = $parts[1];

// ...or...

$domain = ltrim($host, 'www.')

If your url includes "www." or not you get the same end result, i.e. "example.co.uk"

Voilà!

like image 36
user3251285 Avatar answered Oct 07 '22 00:10

user3251285