I want to remove "&start=2" from a given URL. This is what I tried:
$uri = "http://test.com/test/?q=Marketing&start=2";
$newuri = str_replace("&start=","",$url);
echo $newuri;
I want to remove "&start=2" from a given URL. This is what I tried:
$uri = "http://test.com/test/?q=Marketing&start=2";
$newuri = str_replace("&start=","",$url);
echo $newuri;
You'll want to use preg_replace instead for this:
$newuri = preg_replace('/&start=(\d+)/','',$uri);
You are passing $url as an argument to str_replace. But the variable that has the url is called $uri.
$uri = "http://test.com/test/?q=Marketing&start=2";
$newuri = str_replace("&start=2","",$uri);
...
2 of start as the OP requires. A generic solution allowing for arbitrary numbers would need a regular expression replacement function.Just to throw a regex-free solution out there:
// Grab the individual components of the URL
$uri_components = parse_url($uri);
// Take the query string from the url, break out the key:value pairs
// then put the keys and values into an associative array
foreach (explode('&', $uri_components['query']) as $pair) {
list($key,$value) = explode('=', $pair);
$query_params[$key] = $value;
}
// Remove the 'start' pair from the array and start reassembling the query string
unset($query_params['start']);
foreach ($query_params as $key=>$value)
$value ? $new_query_params[] = $key."=".$value : $new_query_params[] = $key;
// Now reassemble the whole URL (including the bits removed by parse_url)
$uri_components['scheme'] .= "://";
$uri_components['query'] = "?".implode($new_query_params,"&");
$newuri = implode($uri_components);
Admittedly it's massively verbose compared to the regex-based solutions, but it might provide some extra flexibility down the line?
Try This regex free solution:
$uri = "http://test.com/test/?q=Marketing&start=2";
$QueryPos = strpos($uri, '&start='); //find the position of '&start='
$newURI = substr($uri, 0, -(strlen($uri)-$QueryPos)); //remove everything from the start of $QueryPos to end
echo $newURI; //OUTPUT: http://test.com/test/?q=Marketing