URL エンコードとデコード

以下のスクリプトには、UTF-8 版 newLISP が必要です。

 文字コードが UTF-8 のURLエンコードは、前に紹介していますが、UTF-8版でない newLISP 用です。
 今回は、Windows でも使えるようになった UTF-8版 newLISP 用です(笑)。
 先ずは、エンコードから、

(define (char2hex ch pre flag , (d 64))
  (if (and flag (< ch 128)) (char ch)
    (let (u 0 res '())
      (while (> ch 127)
        (push (string pre (format "%2X" (+ 0x80 (% ch d)))) res)
        (setq ch (/ ch d))
        (setq u (+ 0x80 (>> u))))
      (push (string pre (format "%2X" (if (= u 0) ch (+ 0x80 (>> u) ch)))) res)
      (apply string res))))
(define (url-encode-utf8 str (pre "%") flag)
  (let (res "")
    (dostring (c str)
      (extend res (char2hex c pre flag)))))

 使い方は、

> (url-encode-utf8 "技術")
"%E6%8A%80%E8%A1%93"
> (url-encode-utf8 "技術" "")
"E68A80E8A193"
> 

 % を外せるようにした訳は、別の機会に(笑)。
 newLISP の Code Snippets にある “URL encode and decode” を参考にして、

(define (url-encode str)  
  (replace {([^a-zA-Z0-9])+} str (url-encode-utf8 $0) 0))

 と定義すれば、

> (url-encode "web技術")
"web%E6%8A%80%E8%A1%93"
> (url-encode "科学 to 技術")
"%E7%A7%91%E5%AD%A6%20to%20%E6%8A%80%E8%A1%93"
> 

 こんな感じ。
 さて、デコードは、

(module "macro.lsp")
(macro (hex2int H)  (int H 0 16))
(define (url-decode-utf8 str (pre "%"))
  (let (hexs (1 (parse str pre))
        res '())
    (while hexs
      (let (ch (hex2int (pop hexs)))
        (if (< ch 0x80) (push ch res -1)
            (< ch 0xE0) (push (+ (* 0x40 (& (hex2int ch) 0x1F))
                                 (& (hex2int (pop hexs)) 0x3F)) res -1)
            (< ch 0xF0) (push (+ (* 0x1000 (& (hex2int ch) 0x0F))
                                 (* 0x40 (& (hex2int (pop hexs)) 0x3F))
                                 (& (hex2int (pop hexs)) 0x3F)) res -1)
            (< ch 0xF8) (push (+ (* 0x40000 (& (hex2int ch) 0x07))
                                 (* 0x1000 (& (hex2int (pop hexs)) 0x3F))
                                 (* 0x40 (& (hex2int (pop hexs)) 0x3F))
                                 (& (hex2int (pop hexs)) 0x3F)) res -1)
             )))
    (apply string (map char res))))

 使い方は、

> (url-decode-utf8 "%E6%8A%80%E8%A1%93")
"技術"
> (url-decode-utf8 (append "%" (join (explode "E68A80E8A193" 2) "%")))
"技術"
> 

 何をしたいのか、一目瞭然?(笑)
 こちらも、newLISP の Code Snippets にある “URL encode and decode” を参考にして、

(define (url-decode str)
  (replace "+" str " ") ; optional
  (replace "(%[0-9A-F][0-9A-F])+" str (url-decode-utf8 $0) 0))

 と定義すれば、

> (url-decode "web%E6%8A%80%E8%A1%93")
"web技術"
> (url-decode "%E7%A7%91%E5%AD%A6%20to%20%E6%8A%80%E8%A1%93")
"科学 to 技術"
> (url-decode "%E7%A7%91%E5%AD%A6+to+%E6%8A%80%E8%A1%93")
"科学 to 技術"
> 

 こんな感じで使えます。

 以上、如何でしょうか?

No comments yet

コメントを残す