Take the 2-minute tour ×
Code Review Stack Exchange is a question and answer site for peer programmer code reviews. It's 100% free, no registration required.

Is this the best way to remove URL parameters from a string containing an URL?

$url = "http://www.test.com/test.html?parameter=hey&parameter2=ho";
if (strstr($url, "?")) {
   $url = strstr($url, "?", true);
}

Is there a better one-line solution? It seems so bad to run the same function twice.

share|improve this question

2 Answers 2

There are built-in functions for this purpose, in PHP.


First you split the different part of the url : $parsedUrl = parse_url($url);

Here is the part you're looking for : $queryPart = $parsedUrl["query"];

You can split this query in parts with parse_str($queryPart, $_QUERY);

And Voilà ! var_dump($_QUERY);

You now can remove what you want from the $_QUERY Array : unset($_QUERY['parameter']);

And construct the Query String back : $queryPart = http_build_query($_QUERY);

Put the query back in the $parsed_url : $parsedUrl["query"] = $_QUERY;

And finally reconstruct the url : http_build_url('', $parsedUrl["query"] );


Here you go : http://php.net/manual/en/function.parse-url.php

share|improve this answer
$url = 'http://www.test.com/test.html?parameter=hey&parameter2=ho';
if ( $temp = strstr($url, '?', true) ) {
   $url = $temp;
}

If you just want to get rid of the second call, you can save the value in a variable. If it exists, do the assignment. If not, don't.

In PHP, if you don't need to do string interpolation (variables embedded in strings), you can just use single quotes. This is slightly faster and can help avoid bugs where you accidentally interpret something as a variable that was meant to be a literal $.

Note: there may be better overall solutions, but with so little context, it is hard to see them. For example, you don't say how you get this URL. Or what you're going to do with it. There might be better changes in one of those places.

share|improve this answer

Your Answer

 
discard

By posting your answer, you agree to the privacy policy and terms of service.

Not the answer you're looking for? Browse other questions tagged or ask your own question.