$uri = "http://test.com/test/?q=Marketing&start=2";
$newuri = str_replace("&start=","",$url);
// I want to remove "&start=2"
echo $newuri;
views:
110answers:
4
+5
A:
You'll want to use preg_replace instead for this:
$newuri = preg_replace('/&start=(\d+)/','',$uri);
brianreavis
2009-10-15 09:05:10
It's unnecessary to capture the \d+ in parentheses
Ben James
2009-10-15 09:21:17
Right... but it helps from a readability standpoint. Not critical in this example, but it's good practice for when gigantic regex patterns come around.
brianreavis
2009-10-15 09:23:10
As the asker is a beginner, perhaps a little more elaboration as to what the code is doing?
random
2009-10-15 09:36:34
A:
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)
Ben James
2009-10-15 09:05:29
+3
A:
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);
...
rogeriopvl
2009-10-15 09:06:09
This won't actually remove the numeric value `2` of `start` as the OP requires. A generic solution allowing for arbitrary numbers would need a regular expression replacement function.
pavium
2009-10-15 09:13:55
+1
A:
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?
Rich Pollock
2009-10-15 10:03:27