Reputation: 11124
Suppose I have the following, which is the current url:
http://myurl.com/locations/?s=bricks&style=funky-quirky+rustic&feature=floors-concrete+kitchen+bathroom
How would I remove all parameters except S
using PHP? In other words, just leaving: http://myurl.com/locations/?s=bricks
The other parameters will always be Style, Type, Feature, and Area, and some or all of them may be present.
Thanks!
Upvotes: 0
Views: 1540
Reputation: 13371
If you know that s
will always be the first parameter, then you can simply do:
$url = "http://myurl.com/locations/?s=bricks&style=funky-quirky+rustic&feature=floors-concrete+kitchen+bathroom";
$split = explode('&',$url);
echo $split[0];
However, if the position of s
in the parameters is unkown, then you can do this:
$url = "http://myurl.com/locations/?s=bricks&style=funky-quirky+rustic&feature=floors-concrete+kitchen+bathroom";
$split = explode('?',$url);
parse_str($split[1],$params);
echo $split[0].'?s='.$params['s'];
Upvotes: 1
Reputation: 24413
parse_str(parse_url($url, PHP_URL_QUERY), $query);
$newurl = 'http://myurl.com/locations/?s=' . $query['s'];
Upvotes: 1
Reputation: 21476
if ( isset($_GET['s']) && count($_GET) > 1 ) {
header('Location: ?s='. rawurlencode($_GET['s']));
exit;
}
Edited to somewhat appease Jon.
Upvotes: 1
Reputation: 6930
You can achieve this in several different manners.
I will show you the best standard I ever faced to work with urls:
$originUrl = parse_url('http://myurl.com/locations/?s=bricks&style=funky-quirky+rustic&feature=floors-concrete+kitchen+bathroom');
parse_str($originUrl['query'], $queryString);
echo $newUrl = $originUrl['scheme'].'://'.$originUrl['host'].$originUrl['path'].'?s='.$queryString['s'];
Good Luck!
Upvotes: 1
Reputation: 437854
Not much in the way of error checking, but if s
is guaranteed to exist this will work:
list($base, $query) = explode('?', $url);
parse_str($query, $vars);
$result = $base.'?s='.rawurlencode($vars['s']);
It will also work no matter in what position s
appears in the query string. I 'm doing a minimal initial "parsing" step with explode
, but if that doesn't feel right you can always bring in the big guns and go with parse_url
instead at the expense of being much more verbose.
Upvotes: 1