如果我有一个网址,例如 www.example.com/test/example/product.html
我怎样才能获得测试部分(所以最高级别)
我知道您会使用$_SERVER['REQUEST_URI']
,也许substr
或trim
但我不确定该怎么做,谢谢!
答案 0 :(得分:19)
将字符串拆分为包含explode
的数组,然后获取所需的部分。
$whatINeed = explode('/', $_SERVER['REQUEST_URI']);
$whatINeed = $whatINeed[1];
如果使用PHP 5.4,则可以执行$whatINeed = explode('/', $_SERVER['REQUEST_URI'])[1];
答案 1 :(得分:5)
<?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
*/