如何动态查找和删除网站路径URI的最后一个子项?
代码:$uri = $_SERVER["REQUEST_URI"];
结果:http://192.168.0.16/wordpress/blog/page-2/
期望的结果:http://192.168.0.16/wordpress/blog/
非常感谢提前!
答案 0 :(得分:1)
你可以使用它,你可以获得所需的输出:
// implode string into array
$url = "http://192.168.0.16/wordpress/blog/page-2/";
//then remove character from right
$url = rtrim($url, '/');
// then explode
$url = explode('/', $url);
// remove the last element and return an array
json_encode(array_pop($url));
// implode again into string
echo implode('/', $url);
另一种方法是:
// implode string into array
$url = explode('/', 'http://192.168.0.16/wordpress/blog/page-2/');
//The array_filter() function filters the values of an array using a callback function.
$url = array_filter($url);
// remove the last element and return an array
array_pop($url);
// implode again into string
echo implode('/', $url);
答案 1 :(得分:0)
$url = 'http://192.168.0.16/wordpress/blog/page-2/';
// trim any slashes at the end
$trim_url = rtrim($url,'/');
// explode with slash
$url_array = explode('/', $trim_url);
// remove last element
array_pop($url_array);
// implade with slash
echo $new_url = implode('/', $url_array);
输出:
http://192.168.0.16/wordpress/blog
答案 2 :(得分:0)
正确的方法是使用parse_url()和dirname(),它们也支持查询参数。你可以爆炸$uri['path']
,但在这种情况下它是不必要的。
<?php
// explode the uri in its proper parts
$uri = parse_url('/wordpress/blog/page-2/?id=bla');
// remove last element
$path = dirname($uri['path']);
// incase you got query params, append them
if (!empty($uri['query'])) {
$path .= '?'.$uri['query'];
}
// string(22) "/wordpress/blog?id=bla"
var_dump($path);
看到它正常工作: https://3v4l.org/joJrF