PHP get URI parts of URL

2020-03-15 05:40发布

I have 2 strings and substitute them, so I get just URI parts.

$base_url = 'http://localhost/project/';
$url      = 'http://localhost/project/controller/action/param1/param2';

I am checking for URI parts.

$only_segments = str_replace($base_url, '', $real_url);

Basicly I do: {url} - {base_url} = {only_segments}

Then I can get segments:

$parts = explode('/', $only_segments);
print_r($parts);

Question:

Am I on right path or can it be done easier with $_SERVER['REQUEST_URI'] ?

Note: I don't want project in URI parts, it is sub-folder of localhost.

标签: php uri
2条回答
来,给爷笑一个
2楼-- · 2020-03-15 05:50

Look into parse_url(). That will get you most of the way there. All you would need to do is remove the portion of the path that is part of your base URL.

print_r(parse_url('http://localhost/project/controller/action/param1/param2'));

Array
(
    [scheme] => http
    [host] => localhost
    [path] => /project/controller/action/param1/param2
)
查看更多
小情绪 Triste *
3楼-- · 2020-03-15 05:51

A more complete Example:

var_dump(parse_url(http://lambo-car-dealer.com/Lambo/All+Models/2018/?limits=10&advance_options=no));

output:

array(4) {
  ["scheme"]=>
  string(4) "http"
  ["host"]=>
  string(48) "lambo-car-dealer.com"
  ["path"]=>
  string(44) "/Lambo/All+Models/2018/"
 ["query"]=>
 string(121) "limits=10&advance_options=no"

}

Also can get it this way:

$URL = "http://$_SERVER[HTTP_HOST]$_SERVER[REQUEST_URI]";
$URI = "$_SERVER[REQUEST_URI]";
查看更多
登录 后发表回答