상세 컨텐츠

본문 제목

[PHP] 자바스크립트의 escape(), unescape() 함수 인코딩/디코딩 문자열 처리

인터넷/프로그래밍/홈페이지

by 길상여의 2008. 9. 5. 17:18

본문


/*
* javascript-x escape 대응함수
*/
function unescape($text) {
 return urldecode(preg_replace_callback('/%u([[:alnum:]]{4})/', create_function( '$word', 'return iconv("UTF-16LE", "UHC", chr(hexdec(substr($word[1], 2, 2))).chr(hexdec(substr($word[1], 0, 2))));' ), $text));
}

/*
* javascript-x escape 대응함수
*/
function escape($str) {
 $len = strlen($str);
 for($i=0,$s='';$i<$len;$i++) {
  $ck = substr($str,$i,1);
  $ascii = ord($ck);
  if($ascii > 127) $s .= '%u'.toUnicode(substr($str, $i++, 2));
  else $s .= (in_array($ascii, array(42, 43, 45, 46, 47, 64, 95))) ? $ck : '%'.strtoupper(dechex($ascii));
 }
 return $s;
}

function toUnicode($word) {
 $word = iconv('UHC', 'UTF-16LE', $word);
 return strtoupper(str_pad(dechex(ord(substr($word,1,1))),2,'0',STR_PAD_LEFT).str_pad(dechex(ord(substr($word,0,1))),2,'0',STR_PAD_LEFT));
}


관련글 더보기