Strip off URL parameter with PHP
Solution 1:
The safest "correct" method would be:
- Parse the url into an array with
parse_url()
- Extract the query portion, decompose that into an array using
parse_str()
- Delete the query parameters you want by
unset()
them from the array - Rebuild the original url using
http_build_query()
Quick and dirty is to use a string search/replace and/or regex to kill off the value.
Solution 2:
In a different thread Justin suggests that the fastest way is to use strtok()
$url = strtok($url, '?');
See his full answer with speed tests as well here: https://stackoverflow.com/a/1251650/452515
Solution 3:
This is to complement Marc B's answer with an example, while it may look quite long, it's a safe way to remove a parameter. In this example we remove page_number
<?php
$x = 'http://url.com/search/?location=london&page_number=1';
$parsed = parse_url($x);
$query = $parsed['query'];
parse_str($query, $params);
unset($params['page_number']);
$string = http_build_query($params);
var_dump($string);
Solution 4:
parse_str($queryString, $vars);
unset($vars['return']);
$queryString = http_build_query($vars);
parse_str
parses a query string, http_build_query
creates a query string.
Solution 5:
function removeParam($url, $param) {
$url = preg_replace('/(&|\?)'.preg_quote($param).'=[^&]*$/', '', $url);
$url = preg_replace('/(&|\?)'.preg_quote($param).'=[^&]*&/', '$1', $url);
return $url;
}