Search code examples
phparraysstr-replacefriendly-url

Grab first directory of URL with php array or search/replace


I a URL that looks like this:

http://www.site.com/subdomain1/product/123123/variable-text-goes-here

I'm trying to extract the first directory in the URL, or /subdomain1/

I don't really care how I get it, either through a wildcard replace or by breaking apart the URL into an array. Unfortunately, I'm not having much luck either way.

Some important points: a) /product/ will always be the same exact text "product" b) the number and variable-text parts of the url (last 2 bits) are totally variable. c) The subdomain1 part is also variable

Here's my code:

<?php 
$r = $_SERVER['REQUEST_URI']; 
$test1 = explode('/', $kevtest, 1);
echo 'This is the directory - '.$test1;
 ?>

The results on the page look like this:

This is the directory - Array

I'm not so familiar with Arrays, so I'm not having any luck pulling out the results of the array.

Alternatively, it would be just fine to search/replace out the rest of the variable URL to get me the first part of the URL.

$test1 = str_replace("/product/ (how to I wildcard here?)","",$r);

Solution

  • $url = 'http://example.com/subdomain1/product/123123/variable-text-goes-here';
    $path = parse_url($url)['path'];
    echo explode('/', $path)[1];
    

    If your PHP is < 5.4, use this:

    $url = 'http://example.com/subdomain1/product/123123/variable-text-goes-here';
    $urlParts = parse_url($url);
    $path = $urlParts['path'];
    $subdomain = explode('/', $path);
    echo $subdomain[1];