0

I have been trying to get the first subdirectory of a URL using all kinds of string manipulation functions and have been having a lot of trouble. I was wondering if anyone knew of an easy way to accomplish this?

I appreciate any advice, thanks in advance!

http://www.domain.com/pages/images/apple.png //output: pages

www.domain.com/pages/b/c/images/car.png // output: pages

domain.com/one/apple.png // output: one
AnchovyLegend
  • 12,139
  • 38
  • 147
  • 231

3 Answers3

3

You can use php function parse_url();

$url = 'domain.com/one/apple.png';
$path = parse_url($url, PHP_URL_PATH);

$firstSubDir = explode('/', $path)[1]; // [0] is the domain [1] is the first subdirectory, etc.
echo $firstSubDir; //one
AnchovyLegend
  • 12,139
  • 38
  • 147
  • 231
0
function startsWith($haystack, $needle)
{
    return $needle === "" || strpos($haystack, $needle) === 0;
}

$url = "http://www.domain.com/pages/images/apple.png";

$urlArr = explode('/', $url);

echo (startsWith($url, 'http')) ? $urlArr[3] : $urlArr[1]; // Should echo 'pages'

The above should work on both with and without 'http' as url-prefix case.

Aniruddh
  • 7,648
  • 1
  • 26
  • 43
0

An alternative function to get first path from URL (with or without scheme).

function domainpath($url = '')
{
    $url        = preg_match("@^https?://@", $url) ? $url : 'http://' . $url;
    $url        = parse_url($url);
    $explode    = explode('/', $url['path']);

    return $explode[1];
}

echo domainpath('http://www.domain.com/pages/images/apple.png');
echo domainpath('https://domain.com/pages/images/apple.png');
echo domainpath('www.domain.com/pages/b/c/images/car.png');
echo domainpath('domain.com/one/apple.png');
Wahyu Kristianto
  • 8,719
  • 6
  • 43
  • 68