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.
parse_url() function with mode PHP_URL_HOST.explode() function to break it into parts using . as delimiter.youtube.com, or www.youtube.com, or %.youtube.comDEMO: 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];
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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With