5

Let's say I have a string like:

url = "https://example.com/user/tr_auth.php?key=34432&cmp_id=344&tr_id={user_id}"

I want to update the cmp_id=344 to be say cmp_id=44553. What's the best way to accomplish this? I can't gsub per say because I don't know what cmp_id might be equal, only that it will be a URL parameter in the string.

It seems like I want to do something like

uri = URI.parse(url)
params = CGI.parse(uri.query)

But then, how do I re-build the string swapping out the cmp_id parameter to be 44553?

Thanks!

3 Answers 3

27

If you are dealing with a web application (and/or Rails as the tag seems to indicate), then you certainly have Rack available. Rack::Utils has methods to parse and build a query.

url = "https://example.com/user/tr_auth.php?key=34432&cmp_id=344&tr_id={user_id}"
uri = URI.parse(url)

query = Rack::Utils.parse_query(uri.query)
# => {"key"=>"34432", "cmp_id"=>"344", "tr_id"=>"{user_id}"}

# Replace the value
query["cmp_id"] = 44553

uri.query = Rack::Utils.build_query(query)
uri.to_s
# => "https://example.com/user/tr_auth.php?key=34432&cmp_id=44553&tr_id=%7Buser_id%7D"

Also note that Rack, by default, escapes the query.

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

Comments

2
url = "https://example.com/user/tr_auth.php?key=34432&cmp_id=344&tr_id={user_id}"
uri = URI.parse(url)
params = CGI.parse(uri.query)
params['cmp_id'] = 44553

new_str = uri.host + uri.path + '?' + params.to_query

Comments

1

First, you can parse the url for params:

require 'cgi'
url = 'https://example.com/user/tr_auth.php?key=34432&cmp_id=344&tr_id={user_id}'
string_params = url.split('?')[1]
hash = CGI::parse(string_params)

Then you can iterate the hash by keys and change values:

hash.keys.each {|key| hash[key]='new value'}
url_params = hash.to_param

Comments

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.