Search code examples
phparraysurlexplode

How can I get an URL's host without schema and ending in php?


I want to explode urls to get the host.

$link = str_replace("www.", "", $_POST['link']);
$part1 = explode("//", $link);
$part2 = explode(".", $part1[1]);
$host = $part2[0];

So if the $_POST['link'] is e.g.

https://www.youtube.com/watch?v=udm5jUA-2bs 

I want to get just youtube. In this first way I get explode() expects parameter 2 to be string, array given" error message.

With this method:

$host = var_dump(parse_url($_POST['link'], PHP_URL_HOST));

I get www.youtube.com but I want only youtube.


Solution

    • Extract the url domain using parse_url() function with mode PHP_URL_HOST.
    • We will use explode() function to break it into parts using . as delimiter.
    • Now, the URL can be of two types, either youtube.com, or www.youtube.com, or %.youtube.com
    • We count the parts, and if they are two, we use the first value, else the second value.

    DEMO: https://3v4l.org/KlErW

    $url_host_parts = explode('.', parse_url($_POST['link'], PHP_URL_HOST));
    $host = (count($url_host_parts) == 2) ? $url_host_parts[0] : $url_host_parts[1];