Never been to DZone Snippets before?

Snippets is a public source code repository. Easily build up your personal collection of code snippets, categorize them with tags / keywords, and share them with the world

About this user

Zeke Sikelianos

« Newer Snippets
Older Snippets »
Showing 1-2 of 2 total  RSS 

Ruby: Escape, Unescape, Encode, Decode, HTML, XML, URI, URL

This example will show you how to escape and un-escape a value to be included in a URI and within HTML.

   1  
   2  require 'cgi'
   3  
   4  # escape
   5  name = "ruby?"
   6  value = "yes"
   7  url = "http://example.com/?" + CGI.escape(name) + '=' + CGI.escape(value) + "&var=T"
   8  # url: http://example.com/?ruby%3F=yes&var=T
   9  html = %(<a href="#{CGI.escapeHTML(url)}">example</a>)
  10  # html: <a href="http://example.com/?ruby%3F=yes&amp;var=T">example</a>
  11  
  12  # unescape
  13  name_encoded = html.match(/http:([^"]+)/)[0]
  14  # name_encoded: http://example.com/?ruby%3F=yes&amp;var=T
  15  href = CGI.unescapeHTML(name_encoded)
  16  # href: http://example.com/?ruby%3F=yes&var=T
  17  query = href.match(/\?(.*)$/)[1]
  18  # query: ruby%3F=yes&var=T
  19  pairs = query.split('&')
  20  # pairs: ["ruby%3F=yes", "var=T"]
  21  name, value = pairs[0].split('=').map{|v| CGI.unescape(v)}
  22  # name, value: ["ruby?", "yes"]
  23  

Reconstruct URL string in PHP

   1  
   2    // find out the domain:
   3    $domain = $_SERVER['HTTP_HOST'];
   4    // find out the path to the current file:
   5    $path = $_SERVER['SCRIPT_NAME'];
   6    // find out the QueryString:
   7    $queryString = $_SERVER['QUERY_STRING'];
   8    // put it all together:
   9    $url = "http://" . $domain . $path . "?" . $queryString;
  10    echo "The current URL is: " . $url . "<br />";
  11    
  12    // An alternative way is to use REQUEST_URI instead of both
  13    // SCRIPT_NAME and QUERY_STRING, if you don't need them seperate:
  14    $url2 = "http://" . $domain . $_SERVER['REQUEST_URI'];
  15    echo "The alternative way: " . $url2;
« Newer Snippets
Older Snippets »
Showing 1-2 of 2 total  RSS