请求uri php:获得第一级

132*_*941 6 php

如果我有一个网址,如 www.example.com/test/example/product.html

我怎样才能获得测试部分(所以顶级)

我知道你会使用$_SERVER['REQUEST_URI']也许substr或者trim

但我不确定如何做到这一点,谢谢!

Sam*_*ane 21

将字符串拆分为数组explode,然后获取所需的部分.

$whatINeed = explode('/', $_SERVER['REQUEST_URI']);
$whatINeed = $whatINeed[1];
Run Code Online (Sandbox Code Playgroud)

如果你使用PHP 5.4,你可以做到 $whatINeed = explode('/', $_SERVER['REQUEST_URI'])[1];

  • 这不应该是$ whatINeed [1]吗?$ _SERVER ['REQUEST_URI']以斜杠开头,结果是第一个URI级别在[1]而不是[0]. (3认同)

Inc*_*ito 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    

*/
Run Code Online (Sandbox Code Playgroud)

  • 嗯,使用parse_url的想法是可以的,但是目录名将返回“ / text / example”-整个目录名。它仅上升一个级别。 (2认同)