Posted By

chrisaiv on 11/07/08


Tagged

ruby unescape urlencoded


Versions (?)

Who likes this?

2 people have marked this snippet as a favorite

inkdeep
webstic


Ruby: Unescape a URLEncoded String


 / Published in: Ruby
 

I needed a quick way to unescape a URL Encoded string. I found 2 chill ways

  1. require 'cgi'
  2.  
  3.  
  4. ##################################
  5. #Method 1: Easy Breezy
  6. ##################################
  7. url = "http%3A%2F%2Fcdn.buzznet.com%2Fassets%2Fvideox%2F3%2F6%2F9%2F6%2F6%2F3%2F1%2Fvid-3696631.flv"
  8.  
  9. url = CGI.unescape( url )
  10. puts url
  11.  
  12. ##################################
  13. #Method 2: Complicated but with more control
  14. ##################################
  15.  
  16. def url_escape(string)
  17. string.gsub(/([^ a-zA-Z0-9_.-]+)/n) do
  18. '%' + $1.unpack('H2' * $1.size).join('%').upcase
  19. end.tr(' ', '+')
  20. end
  21.  
  22. def url_unescape(string)
  23. string.tr('+', ' ').gsub(/((?:%[0-9a-fA-F]{2})+)/n) do
  24. [$1.delete('%')].pack('H*')
  25. end
  26. end
  27.  
  28. puts url_unescape( url )

Report this snippet  

You need to login to post a comment.