要检查是否有?something
after index.php
,您可以使用内置函数parse_url()
,如下所示:
if (parse_url($url, PHP_URL_QUERY)) {
// ?something exists
}
要删除id
,您可以使用parse_str()
,获取查询参数,将它们存储在数组中,然后取消设置特定的id
.
并且由于您还想在从 URL 的查询部分删除特定元素后重新创建 URL,因此您可以使用http_build_query()
.
这是一个功能:
function removeQueryString($url, $toBeRemoved, $match)
{
// check if url has query part
if (parse_url($url, PHP_URL_QUERY)) {
// parse_url and store the values
$parts = parse_url($url);
$scriptname = $parts['path'];
$query_part = $parts['query'];
// parse the query parameters from the url and store it in $arr
$query = parse_str($query_part, $arr);
// if id == x, unset it
if (isset($arr[$toBeRemoved]) && $arr[$toBeRemoved] == $match) {
unset($arr[$toBeRemoved]);
// if there less than 1 query parameter, don't add '?'
if (count($arr) < 1) {
$query = $scriptname . http_build_query($arr);
} else {
$query = $scriptname . '?' . http_build_query($arr);
}
} else {
// no matches found, so return the url
return $url;
}
return $query;
} else {
return $url;
}
}
测试用例:
echo removeQueryString('index.php', 'id', 'x');
echo removeQueryString('index.php?a=11&id=x', 'id', 'x');
echo removeQueryString('index.php?a=11&id=x&qid=51', 'id', 'x');
echo removeQueryString('index.php?a=11&foo=bar&id=x', 'id', 'x');
输出:
index.php
index.php?a=11
index.php?a=11&qid=51
index.php?a=11&foo=bar
演示!