0

I have the following url which will always have a color variable attached:

http://www.example.com/?new=yes&color=red&shape=square

How would I, using PHP, remove everything at the end; starting at &color, so I am left with the following:

http://www.example.com/?new=yes
2
  • What if the order of the parameters differs? Commented Mar 31, 2011 at 18:20
  • They won't. Very few links, this is just for myself. Commented Mar 31, 2011 at 18:21

3 Answers 3

3

The literal answer to your question is:

$url = substr($url, 0, strpos($url, '&color='));

However, this is good only for the specific case -- it would probably be a good idea to do something a little more robust. For example, splitting the URL, getting the key/value pairs into an array, removing those you don't want (or removing everything except those you want) and recreating the URL.

Sign up to request clarification or add additional context in comments.

3 Comments

Thanks for taking the time to reply, perfect job!
What if the needle is not contained?
@Gumbo: Bad things happen. But I gathered the impression from the OP's comment that this is throwaway code, and it's hard to argue against a single LOC if that's true.
2
$url = "http://www.example.com/?new=yes&color=red&shape=square";

$url_parts = explode("&", $url);

$thePartYouWant = $url_parts[0];

Comments

2

I would recommend the combination of parse_url & parse_str. You can also use http_build_url & http_build_str, though these require pecl_http.

5 Comments

And thanks for the reply Brad, will take a look at those functions
While this approach is what I view as "most correct" (and better than the shameful hack that is my answer), it has a big practical flaw: http_build_url and friends is not built in by default.
@Jon: Indeed. Part of the PECL lib, though intended as the most "bullet-proof" solution.
I 'm only saying because the other day I was going to recommend exactly this for another question; when I found out that it wasn't built in and my "example" code was going above 1 screen size on its quest for correctness, I gave up.
@Jon: I hear ya, I've had those days... ;-)

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.