While implementing client support for OAuth authentication for Twitter, I needed a url encoding procedure that strictly conforms to RFC 3986, which ns_urlencode and ad_urlencode do not. This is necessary for the HMAC signatures used in OAuth. RFC 3986 only has four reserved characters apart from ASCII letters and numbers: _.-~
Here's the code I used, in case anyone else needs it in the future:
set enc [ns_urlencode $string]
set enc [string map -nocase {%2d - %5f _ %2e . + %20 %7e ~} $enc]
# Capitalize
set map [list]
foreach {m c} [regexp -all -inline {%([a-f][0-9a-f]|[0-9a-f][a-f])} $enc] {
if { ![info exists matched($m)] } {
lappend map $m [string toupper $m]
set matched($m) ""
}
}
set enc [string map $map $enc]
There's probably a better way of capitalizing the codes.