I have a function to clean a link when I filter my search results
function cleanLink($url,$remove){
$aQ = explode("&",str_replace("?", "", $url));
foreach ($aQ as $part) {
$pos = strpos($part, $remove);
if ($pos === false)
$queryClean[] = $part;
}
$line = implode("&", $queryClean);
return "?".$line;
}
$linkACTUAL = "".$_SERVER["QUERY_STRING"];
cleanLink($linkACTUAL, "q=");
echo $linkACTUAL."&q=".$word;
This works fine, for example if my url is
www.mysite.com/?q=wordx
I want to add an "order alphabetic desc" so my url returns
www.mysite.com/?q=wordx&order=desc
but if my query string is empty (e.g. www.mysite.com/
) the return is
www.mysite.com/?&q=word
How can I remove the &
if the query string is empty?
If your function is running fine when there are query string then you can simply put your function call inside if statement like
if(!empty($_GET))
{
$linkACTUAL = "".$_SERVER["QUERY_STRING"];
cleanLink($linkACTUAL, "q=");
echo $linkACTUAL."&q=".$word;
}
Updated:
echo (false === strpos($linkACTUAL, "&")) ? $linkACTUAL."q=".$word : $linkACTUAL."&q=".$word;
Change
if ($pos === false)
to
if ($pos === false && $part)
to omit empty $part string (will evaluate as false). You also should initialize $queryClean
$queryClean = array();
You can use parse_str and http_build_str to remove a parameter from the query string. You just to make sure pecl_http >= 0.23.0 is installed
function cleanLink($queryString, $remove)
{
parse_str($queryString, $query);
if (array_key_exists($remove, $query)) {
unset($query[$remove]);
}
return http_build_str($query);
}
$linkACTUAL = $_SERVER["QUERY_STRING"];
cleanLink($linkACTUAL, "q");
echo $linkACTUAL . "&q=" . $word;
For more information see http://php.net/manual/en/function.http-build-str.php and http://php.net/manual/de/function.parse-str.php