使用 parse url()

parse_url():此函数解析 URL 并返回一个关联数组,该数组包含存在的 URL 的各种组件。

$url = parse_url('http://example.com/project/controller/action/param1/param2');

Array
(
    [scheme] => http
    [host] => example.com
    [path] => /project/controller/action/param1/param2
)

如果你需要分隔路径,则可以使用 explode

$url = parse_url('http://example.com/project/controller/action/param1/param2');
$url['sections'] = explode('/', $url['path']);

Array
(
    [scheme] => http
    [host] => example.com
    [path] => /project/controller/action/param1/param2
    [sections] => Array
        (
            [0] => 
            [1] => project
            [2] => controller
            [3] => action
            [4] => param1
            [5] => param2
        )

)

如果你需要本节的最后一部分,可以像这样使用 end()

$last = end($url['sections']);

如果 URL 包含 GET 变量,你也可以检索它们

$url = parse_url('http://example.com?var1=value1&var2=value2');

Array
(
    [scheme] => http
    [host] => example.com
    [query] => var1=value1&var2=value2
)

如果你想分解查询变量你可以像这样使用 parse_str()

$url = parse_url('http://example.com?var1=value1&var2=value2');
parse_str($url['query'], $parts);

Array
(
    [var1] => value1
    [var2] => value2
)