Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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.

like image 629
user7425848 Avatar asked Nov 19 '25 02:11

user7425848


2 Answers

  • 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];
like image 142
Madhur Bhaiya Avatar answered Nov 20 '25 18:11

Madhur Bhaiya


what about this without any regex? You can use parse_url() and explode() to get what you want i.e youtube

<?php
$url = 'https://www.youtube.com/watch?v=udm5jUA-2bs';
$parse = parse_url($url);
//print_r($parse);
echo explode('.',$parse['host'])[1];
?>

Output:

 youtube

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

like image 31
Always Sunny Avatar answered Nov 20 '25 18:11

Always Sunny



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!