- # urlString.tcl -- urlEncode or urlDecode a string
- #
- # Description :
- # string Functions
- # urlencode: URL-encodes a string. (http://www2.tcl.tk/14144)
- # urldecode: URL-decodes a URL-encoded string. (http://www2.tcl.tk/14144)
- #
-
-
-
- package provide urlString 1.0
- package require Tcl 8.3
-
- namespace eval ::urlString:: {
- namespace export urlencode
- namespace export urldecode
- }
-
-
-
- proc ::urlString::urlencode {string} {
- variable map
- variable alphanumeric a-zA-Z0-9
- for {set i 0} {$i <= 256} {incr i} {
- set c [format %c $i]
- if {![string match \[$alphanumeric\] $c]} {
- set map($c) %[format %.2x $i]
- }
- }
- # These are handled specially
- array set map { " " + \n %0d%0a }
-
- # The spec says: "non-alphanumeric characters are replaced by '%HH'"
- # 1 leave alphanumerics characters alone
- # 2 Convert every other character to an array lookup
- # 3 Escape constructs that are "special" to the tcl parser
- # 4 "subst" the result, doing all the array substitutions
-
- regsub -all \[^$alphanumeric\] $string {$map(&)} string
- # This quotes cases like $map([) or $map($) => $map(\[) ...
- regsub -all {[][{})\\]\)} $string {\\&} string
- return [subst -nocommand $string]
- }
-
- proc ::urlString::urldecode {str} {
-
- variable map
- variable alphanumeric a-zA-Z0-9
- for {set i 0} {$i <= 256} {incr i} {
- set c [format %c $i]
- if {![string match \[$alphanumeric\] $c]} {
- set map($c) %[format %.2x $i]
- }
- }
- # These are handled specially
- array set map { " " + \n %0d%0a }
- # rewrite "+" back to space
- # protect \ from quoting another '\'
- set str [string map [list + { } "\\" "\\\\"] $str]
-
- # prepare to process all %-escapes
- regsub -all -- {%([A-Fa-f0-9][A-Fa-f0-9])} $str {\\u00\1} str
-
- # process \u unicode mapped chars
- return [subst -novar -nocommand $str]
- }
-
- # ------------------ END OF FILE ------------------