所以我试图从数组中预定义的 URL 查询字符串中删除特定参数。这是我到目前为止所拥有的:
<?php
// Construct the current page URL
$host = $_SERVER['HTTP_HOST'];
$script = $_SERVER['SCRIPT_NAME'];
$params = $_SERVER['QUERY_STRING'];
$currentUrl = 'http://' . $host . $script . '?' . $params;
// Store all URL parameters into an array (HOST, PATH, QUERY, etc)
$url_params = array();
$url_params = parse_url($currentUrl);
// Create an array to store just the query string, breaking them apart
$params_array = explode('&', $url_params['query']);
// Array holding URL parameters that we want to remove
$params_to_remove = array("param1", "param2", "param3", "param4", "param5");
$location = 0;
// Loop through and remove parameters found in PARAMS_TO_REMOVE array
for($x = 0; $x < count($params_to_remove); $x++) {
if(in_array($params_to_remove[$x], $params_array)) {
$location = array_search($params_to_remove[$x], $params_array);
unset($params_array[$location]);
}
}
// Print array after unwanted parameters were removed
print_r($params_array);
echo '<br /><br />';
// Construct a new array holding only the parameters that we want
$clean_params_array = array();
for($z = 0; $z < count($params_array); $z++) {
if($params_array[$z] != '') array_push($clean_params_array, $params_array[$z]);
}
// Print clean array
print_r($clean_params_array);
echo '<br />';
// Construct the new URL
// If there are paramters remaining in URL reconstruct them
if(count($clean_params_array) > 0) {
$final_url = 'http://www.example.com' . $url_params['path'] . '?';
for($y = 0; $y < count($clean_params_array); $y++) {
$final_url .= $clean_params_array[$y] . '&';
}
// Trim off the final ampersand
$final_url = substr($final_url, 0, -1);
}
// No parameters in final URL
else $final_url = 'http://www.example.com' . $url_params['path'];
// Print final URL
echo '<br />' . $final_url;
?>
这是输出:
使用http://www.example.com/test.php?apple&banana&orange¶m1&strawberry¶m2&pineapple
Array ( [0] => apple [1] => banana [2] => orange [4] => strawberry [6] => pineapple )
Array ( [0] => apple [1] => banana [2] => orange [3] => strawberry )
http://www.example.com/test.php?apple&banana&orange&strawberry
如您所见,我丢失了最后一个参数。我也觉得好像我太啰嗦了……我哪里错了?