0

I am having several urls, such as:

http://stackoverflow.com
https://google.com
facebook.com
cnn.com/
https://help.uber.com/

I would only like to get back for every url the middle part, such as:

facebook, cnn, uber, stackoverflow, google.

I tried the following, where $line is the url:

$parts = parse_url($line);
$path_parts = explode('/', $parts['path']);
echo $path_parts[count($path_parts)-1];

However, as a return I do not get anything echoed out. The urls are also correctly read in!

Any suggestions what I am doing wrong?

I appreciate your replies!

Carol.Kar
  • 4,581
  • 36
  • 131
  • 264
  • 2
    You can check [this](https://stackoverflow.com/questions/276516/parsing-domain-from-url-in-php) and do the removing `.com or any other .something` yourself. – hungrykoala Jun 28 '18 at 05:02

2 Answers2

3

Try using host like this. if your giving url like cnn.com parse_url parse it and will store it in path index.

<?php

$line='https://help.uber.com/';
$parts = parse_url($line);
$path_parts = explode('.', isset($parts['host'])?$parts['host']:$parts['path']);
echo $path_parts[count($path_parts)-2];

?>
JYoThI
  • 11,977
  • 1
  • 11
  • 26
1

You have to get the details first and use preg_match to get the format . Check the code below and you will get your desired output .

<?php

    $line = "stackoverflow.com" ;
    $parts = parse_url($line);
    $domain_name = isset($parts['host']) ? $parts['host'] : $parts['path'];
    if (preg_match('/(?P<domain>[a-z0-9][a-z0-9\-]{1,63}\.[a-z\.]{2,6})$/i', $domain_name, $dom)){
        $d_name = explode(".", $dom['domain']) ;
        echo $d_name[0];
    }

?>
PHP Web
  • 257
  • 3
  • 8