Any one have the ultimate PHP function(s) to add/remove parameters from a query string? It needs to handle all possible cases, Ive seen ones that handle some cases, but not all.
Some example cases:
- http://mysite.com?param1=1¶m2=2
- http://www.mysite.com/?param1[]=1¶m1[]=2
- ftp://user:pass@mysite.com/files/uploads/?param1=1¶m2=2
- /?param1=1¶m2=2
- /page.html?param1=1
- /dir/page.html?test=1&bla=2
- /dir/page.html?param1=1#jump_to_bottom
It should ideally be something like:
function add_get_param($uri, $name, $value = null) { ... }
function remove_get_param($uri, $name) { ... }
Some example tests:
$var = add_get_param('http://mysite.com?param1=1¶m2=2', 'param3', 3);
// http://mysite.com?param1=1¶m2=2¶m3=3
and:
$var = add_get_param('/dir/page.html?param1=1¶m2=2#jump_to_bottom', 'param3');
// /dir/page.html?param1=1¶m2=2¶m3#jump_to_bottom
etc...
Alright, I wrote my own functions:
PHP: http://pastebin.org/170157 jQuery: http://pastebin.org/169981
This is the sketch for the function you can start with:
UPD: since
parse_str
breaks the data (replaces dots with underscores) I don't think this sketch is useful.I don't know about the ultimate solution. But PHP has several very helpful native functions that making your own defined function about should be easy.
Check out: html_build_query(), parse_str(), and parse_url()
Alright I wrote my own, based on zerkms's sketch
And here is my limited test cases:
I also converted it to JavaScript/jQuery
And the limited text cases:
try the built in
http_build_query
andparse_str
functions, they use associative arrays in the same style as$_GET
as intermediates, but seem to do what you want...