获取当前网址 PHP 的一部分


Get part of the current url PHP

如何无法获取当前网址的特定部分? 例如,我当前的网址是:

http://something.com/index.php?path=/something1/something2/something3/

好吧,我需要用 php 打印something2

谢谢!

在 PHP 中使用 explode 函数通过第一个参数(在本例中为正斜杠)分隔 URL。为了实现您的目标,您可以使用;

$url = "http://something.com/index.php?path=/something1/something2/something3/";
$parts = explode('/', $url);
$value = $parts[count($parts) - 2];

所有这些其他示例似乎都集中在您的确切示例上。 我的猜测是,您需要一种更灵活的方法来执行此操作,因为如果您的 URL 更改并且您仍然需要从查询字符串中的参数中获取数据path则仅爆炸方法非常脆弱。

我将向您指出parse_url()parse_str()功能。

// your URL string
$url = 'http://something.com/index.php?path=/something1/something2/something3/';
// get the query string (which holds your data)
$query_string = parse_url($url, PHP_URL_QUERY);
// load the parameters in the query string into an array
$param_array = array();
parse_str($query_string, $param_array);
// now you can look in the array to deal with whatever parameter you find useful. In this case 'path'
$path = $param_array['path'];
// now $path holds something like '/something1/something2/something3/'
// you can use explode or whatever else you like to get at this value.
$path_parts = explode('/', trim($path, '/'));
// see the value you are interested in
var_dump($path_parts);

你可以做这样的事情:

$url = explode('/', 'http://something.com/index.php?path=/something1/something2/something3/');
echo $url[5];