Get part of the current url PHP [closed]

北战南征 提交于 2019-12-24 04:01:18

问题


How i cant get a specific part of the current url? for example, my current url is:

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

Well, i need to print something2 with php.

Thanks!


回答1:


You use the explode function in PHP to separate the URL by the first parameter (in this case a forward slash). To achieve your goal you could use;

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



回答2:


All these other example seem to focus on your exact example. My guess is that you need a more flexible way of doing this, as the explode-only approach is very fragile if your URL changes and you still need to get data out of path parameter in query string.

I will point out the parse_url() and parse_str() functions to you.

// 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);



回答3:


You could do something like this:

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


来源:https://stackoverflow.com/questions/19259219/get-part-of-the-current-url-php

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!