Uri php request: get the first level

If I had a url like www.example.com/test/example/product.html

How can I get only the test part (so the top level)

I understand that you would use $_SERVER['REQUEST_URI']and perhaps substrortrim

But I'm not sure how to do this, thanks!

+5
source share
2 answers

Break the string into an array with explode, and then take the part you need.

$whatINeed = explode('/', $_SERVER['REQUEST_URI']);
$whatINeed = $whatINeed[1];

If you are using PHP 5.4, you can do $whatINeed = explode('/', $_SERVER['REQUEST_URI'])[1];

+19
source
<?php
$url = 'http://username:password@hostname.foo.bar/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    

*/
+5
source

All Articles