Forum Moderators: coopster
$r_uri = $_SERVER['QUERY_STRING'];
$r_uri = str_replace("h=" . $_GET['h'], "", $r_uri);
$r_uri = str_replace("q=" . $_GET['q'], "", $r_uri);
$r_uri = str_replace("start=" . $_GET['start'], "", $r_uri);
$r_uri = rtrim($r_uri, "&"); $r_uri = preg_replace('/((h=' . $_GET['h'] . ')|(q=' . $_GET['q'] . ')|(start=' . $_GET['start'] . '))&?/gi, '', $r_uri); $r_uri = false;
foreach ($_GET as $key) {
if ($key != 'h' && $key != 'q' && $key != 'start')
$r_uri .= $key . '=' . $_GET[$key] . '&';
}
if ($r_uri)
$r_uri = rtrim($r_uri, '&'); I could potentially end up with multiple & in a rowYou could always globally replace
I'd not use sprintf() since it's slower than preg_replace or str_replace.
Something like
parse_str($_SERVER['QUERY_STRING'],$res);
@unset($res['h'],$res['q'],$res['start']);
echo http_build_query($res);
You could always globally replace
&{2,} or &&+
with
&
alone, if the && sequence makes you anxious. (It would me :))
I'd think about a pattern involving global delete of
\b(h|q|start)=[^&]*
and then reduce any resulting && separately, because sometimes two steps forward and one back is less bother than doing it all in one step. I said * rather than + in case you accidentally find yourself with a null parameter.
is there any speed difference to use a wildcard versus the real data?It depends what you mean by wildcard. Notably, {site that really ought to know better} is extremely fond of giving examples in the form
...but I really doubt the difference is significant in any real-life application. ...
I always try to make my regex as specific as I can; eg, "h" and "start" will always be a number (if they exist at all) so I could use [0-9]* instead of [^&]*. In theory that would prevent the regex from looking for letters and characters so it should be marginally faster? But then, if I can plug in "123456" instead of [0-9] then it would have even fewer things to consider, in theory making it even faster still.
I'm curious how you were intending to use sprintf() here? It doesn't seem like the right tool for the job, regardless of performance?
$qs = $_GET;
// why did you have @unset? That threw an error for me so I'm guessing it was a typo
unset($qs['h'], $qs['q'], $qs['start']);
// rebuild it manually instead of using http_build_query
if (count($qs) > 0) {
$r_uri .= '?';
foreach ($qs as $key => $val)
$r_uri .= $key . '=' . $val . '&';
}
// removing this had practically no impact on the speed
$r_uri = rtrim($r_uri, '&');
I've read some benchmarks that find a single preg_replace is about 37% slower than a single str_replace.
[edited by: ergophobe at 11:06 pm (utc) on Sep 21, 2019]