The parameters from a URL string can be retrieved in PHP using parse_url() and parse_str() functions. Note: Page URL and the parameters are separated by the ? character. parse_url() Function: The parse_url() function is used to return the components of a URL by parsing it.
URL parameters are made of a key and a value, separated by an equal sign (=). Multiple parameters are each then separated by an ampersand (&).
QueryParam annotation in the method parameter arguments. The following example (from the sparklines sample application) demonstrates using @QueryParam to extract query parameters from the Query component of the request URL.
GET parameters (also called URL parameters or query strings) are used when a client, such as a browser, requests a particular resource from a web server using the HTTP protocol. These parameters are usually name-value pairs, separated by an equals sign = . They can be used for a variety of things, as explained below.
I think you want to turn any given URL string into a HASH?
You can try http://www.ruby-doc.org/stdlib/libdoc/cgi/rdoc/classes/CGI.html#M000075
require 'cgi'
CGI::parse('param1=value1¶m2=value2¶m3=value3')
returns
{"param1"=>["value1"], "param2"=>["value2"], "param3"=>["value3"]}
I found myself needing the same thing for a recent project. Building on Levi's solution, here's a cleaner and faster method:
Rack::Utils.parse_nested_query 'param1=value1¶m2=value2¶m3=value3'
# => {"param1"=>"value1", "param2"=>"value2", "param3"=>"value3"}
Just Improved with Levi answer above -
Rack::Utils.parse_query URI("http://example.com?par=hello&par2=bye").query
For a string like above url, it will return
{ "par" => "hello", "par2" => "bye" }
For a pure Ruby solution combine URI.parse
with CGI.parse
(this can be used even if Rails/Rack etc. are not required):
CGI.parse(URI.parse(url).query)
# => {"name1" => ["value1"], "name2" => ["value1", "value2", ...] }
There more than one ways, to solve your problem. Others has shown you the some tricks. I know another trick. Here is my try :-
require 'uri'
url = "http://www.example.com/something?param1=value1¶m2=value2¶m3=value3"
uri = URI(url)
# => #<URI::HTTP:0x89e4898 URL:http://www.example.com/something?param1=value1¶m2=value2¶m3=value3>
URI::decode_www_form(uri.query).to_h # if you are in 2.1 or later version of Ruby
# => {"param1"=>"value1", "param2"=>"value2", "param3"=>"value3"}
Hash[URI::decode_www_form(uri.query)] # if you are below 2.1 version of Ruby
# => {"param1"=>"value1", "param2"=>"value2", "param3"=>"value3"}
Read the method docomentation of ::decode_www_form
.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With