Reputation: 2170
If I had a url such as www.example.com/test/example/product.html
How would I be able to get just the test part(so the top level)
I understand you would use $_SERVER['REQUEST_URI']
and maybe substr
or trim
But I am unsure of how to do this, thank you!
Upvotes: 11
Views: 22350
Reputation: 22941
Simplest way to get the first part of any path is to use strtok()
:
echo strtok($path, '/');
This will work regardless of whether or not it has a leading /
. To do this with a url you can extract the path part with parse_url()
and use the same strtok()
method mentioned above like this:
echo strtok(parse_url($url, PHP_URL_PATH), '/')
Upvotes: 0
Reputation: 18706
Split the string into an array with explode
, and then take the part you need.
$whatINeed = explode('/', $_SERVER['REQUEST_URI']);
$whatINeed = $whatINeed[1];
If you use PHP 5.4, you can do $whatINeed = explode('/', $_SERVER['REQUEST_URI'])[1];
Upvotes: 31
Reputation: 20765
<?php
$url = 'http://username:[email protected]/test/example/product.html?arg=value#anchor';
print_r(parse_url($url));
$urlArray = parse_url($url);
/* Output:
Array
(
[scheme] => http
[host] => hostname
[user] => username
[pass] => password
[path] => /test/example/product.html
[query] => arg=value
[fragment] => anchor
)
*/
echo dirname($urlArray[path]);
/* Output:
/test
*/
Upvotes: 5