我想从URL中取出一个参数,而不知道它是哪个参数,然后再次重新组合URL.
我想这不是很难用CGI或者URI自己编写的东西,但是我想像这样的功能已经存在了.有什么建议么?
在:
http://example.com/path?param1=one¶m2=2¶m3=something3
日期:
http://example.com/path?param2=2¶m3=something3
解决方法
可寻址的宝石会很好地做到这一点;请看“天男”的上级答案.但是,如果你想自己滚动,这是怎么回事.唯一要求这个代码优雅的是它在一个方法中隐藏了丑陋:
#!/usr/bin/ruby1.8 def reject_param(url,param_to_reject) # Regex from RFC3986 url_regex = %r"^(([^:/?#]+):)?(//([^/?#]*))?([^?#]*)(\?([^#]*))?(#(.*))?$" raise "Not a url: #{url}" unless url =~ url_regex scheme_plus_punctuation = $1 authority_with_punctuation = $3 path = $5 query = $7 fragment = $9 query = query.split('&').reject do |param| param_name = param.split(/[=;]/).first param_name == param_to_reject end.join('&') [scheme_plus_punctuation,authority_with_punctuation,path,'?',query,fragment].join end url = "http://example.com/path?param1=one¶m2=2¶m3=something3" p url p reject_param(url,'param2') # => "http://example.com/path?param1=one¶m2=2¶m3=something3" # => "http://example.com/path?param1=one¶m3=something3"