PHP str_replace at the URL
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);
...
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?
Remember that it is still a valid URI if the position of the querystring elements is changed. So the start
parameter may be the first, hence it may be preceded by a ?
instead of a &
.
So this regex covers both cases:
preg_replace("#[\?&]start=\d+#", '', $uri)
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
if(isset($_GET['start']))
{
$pageNo = $_GET['start'];
$TmpString = '&start='.$pageNo;
$newuri = str_replace($TmpString,"",$url);
// removed "&start=2"
echo $newuri;
}
精彩评论