Page 1 of 1
Remove query parameter from URL in PHP
Posted: 20 May 2018, 07:03
by Marius
How can I remove a parameter from URL query, and display the query string without the removed parameter?
For example, i have this URL:
Code: Select all
domain.net/folder/file.php?x=2&y=3&z=1
I want to remove the "y" parameter and show this query:
Remove query parameter from URL in PHP
Posted: 20 May 2018, 07:19
by Admin
You can use the
queryToArray() function from the following example to make an array from URL query parameters.
With
unset() remove the parameter you want from array.
Then, apply the
http_build_query() function to re-build the query string.
Code: Select all
// Parse out url query string into an associative array
// @param $url String
// @return Array
function queryToArray($url){
$qry = parse_url($url, PHP_URL_QUERY);
parse_str($qry, $re);
return $re;
}
$url ='domain.net/folder/file.php?x=2&y=3&z=1';
$ar_qry = queryToArray($url);
//to see the array
var_export($ar_qry); // array('x'=>'2', 'y'=>'3', 'z'=>'1')
//rebuild and show query string wthout the $except parameter
$except ='y';
unset($ar_qry[$except]);
$qry = http_build_query($ar_qry);
echo $qry; //x=2&z=1