Question

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);
Was it helpful?

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];

OTHER TIPS

Arrays work where you have a key and a value

$var = array('val1', 'val2');
var_dump($var);

Dumps out

array(2) {
  [0]=>
  string(4) "val1"
  [1]=>
  string(4) "val2"
}

0 and 1 are the keys here And you reference them by $var[0], etc. Now, explode works by breaking your string up by the delimiter and returning an array. You can see the contents by using var_dump

$var = explode('/', '/subdomain1/product/123123/variable-text-goes-here');
var_dump($var);

Dumps out

array(5) {
  [0]=>
  string(0) ""
  [1]=>
  string(10) "subdomain1"
  [2]=>
  string(7) "product"
  [3]=>
  string(6) "123123"
  [4]=>
  string(23) "variable-text-goes-here"
}

So... in this case you want to reference

$var[1];

TESTED:

<?php
   $r = $_SERVER['REQUEST_URI']; 
   $test1 = explode('/', $r);
   echo $test1[3]."Array position #3<br />"; 
?>
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top