tags:

views:

110

answers:

4
$uri = "http://test.com/test/?q=Marketing&start=2";

$newuri = str_replace("&start=","",$url);

// I want to remove "&start=2"

echo $newuri;
+5  A: 

You'll want to use preg_replace instead for this:

$newuri = preg_replace('/&start=(\d+)/','',$uri);
brianreavis
It's unnecessary to capture the \d+ in parentheses
Ben James
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
As the asker is a beginner, perhaps a little more elaboration as to what the code is doing?
random
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
+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
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
Fixed. Now it removes the value 2 without using regex.
rogeriopvl
What if they have **3** instead of **2**?
random
+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