使用 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
)