我有這個網址在我的數據庫,在「位置」字段:獲取URL字符串參數?
http://www.youtube.com/watch?v=xxxxxxxxxxxxxxxxxxx
我可以@object.location
得到它,但我怎麼能得到的v
價值?我的意思是,從URL字符串獲取"xxxxxxxxxxxx"
?
我有這個網址在我的數據庫,在「位置」字段:獲取URL字符串參數?
http://www.youtube.com/watch?v=xxxxxxxxxxxxxxxxxxx
我可以@object.location
得到它,但我怎麼能得到的v
價值?我的意思是,從URL字符串獲取"xxxxxxxxxxxx"
?
require 'uri'
require 'cgi'
# use URI.parse to parse the URL into its constituent parts - host, port, query string..
uri = URI.parse(@object.location)
# then use CGI.parse to parse the query string into a hash of names and values
uri_params = CGI.parse(uri.query)
uri_params['v'] # => ["xxxxxxxxxxxxxxxxxxx"]
注意,從CGI.parse
回報是Strings
到Arrays
,以便它可以爲同一個參數名處理多個值的Hash
。對於你的例子,你會想uri_params['v'][0]
。
還要注意,通過CGI.parse
返回將返回Hash
[]
如果請求的關鍵是沒有找到,因此uri_params['v'][0]
將返回值或nil
如果網址不包含v
參數。
$ irb
irb(main):001:0> require 'cgi' => true
irb(main):002:0> test = CGI::parse('v=xxxxxxxxxxxxxxxxxxx') => {"v"=>["xxxxxxxxxxxxxxxxxxx"]}
irb(main):003:0> puts test['v']
xxxxxxxxxxxxxxxxxxx
=> nil
這正是我想要的。我在尋找URI :: HTTP,並找不到任何方法來解析參數。 – AboutRuby 2010-08-23 22:51:50
除了使用庫解析整個URL成爲協議,主機名,路徑和參數,你可以使用一個簡單的正則表達式提取信息。請注意,正則表達式是一個快速而骯髒的解決方案,如果URL的內容完全不同,就會失敗,就像v參數後面有另一個參數一樣。
url = 'http://www.youtube.com/watch?v=xxxxxxxxxxxxxxxxxxx'
video_id = url.match(/\?v=(.+)$/)[1]
你可以通過使用URI :: parse來獲得查詢信息。
url = 'http://www.youtube.com/watch?v=xxxxxxxxxxxxxxxxxxx'
video_id = CGI::parse(URI::parse(url).query)['v']
你不需要加載'net/http'來訪問URI解析。只需要'取代'。 – 2012-07-18 21:59:38
謝謝@theTinMan - 我已經更新了答案。 – mikej 2012-07-19 16:33:07