php模擬js escape(unescape)函數整理

工做中一個項目使用了js escape編碼傳遞參數php程序獲取後需解碼,同時某些特定連接也得編碼,在網絡上收集到了一些函數這裏記錄下php

 

  
  
           
  
  
  1. /** 
  2.  * 類js unescape函數,解碼通過escape編碼過的數據 
  3.  * @param $str 
  4.  */ 
  5. function unescape($str
  6.     $ret = ''
  7.     $len = strlen($str); 
  8.     for ($i = 0; $i < $len$i ++) 
  9.     { 
  10.         if ($str[$i] == '%' && $str[$i + 1] == 'u'
  11.         { 
  12.             $val = hexdec(substr($str$i + 2, 4)); 
  13.             if ($val < 0x7f) 
  14.                 $ret .= chr($val); 
  15.             else  
  16.                 if ($val < 0x800) 
  17.                     $ret .= chr(0xc0 | ($val >> 6)) . 
  18.                      chr(0x80 | ($val & 0x3f)); 
  19.                 else 
  20.                     $ret .= chr(0xe0 | ($val >> 12)) . 
  21.                      chr(0x80 | (($val >> 6) & 0x3f)) . 
  22.                      chr(0x80 | ($val & 0x3f)); 
  23.             $i += 5; 
  24.         } else  
  25.             if ($str[$i] == '%'
  26.             { 
  27.                 $ret .= urldecode(substr($str$i, 3)); 
  28.                 $i += 2; 
  29.             } else 
  30.                 $ret .= $str[$i]; 
  31.     } 
  32.     return $ret
  33. /** 
  34.  * js escape php 實現 
  35.  * @param $string           the sting want to be escaped 
  36.  * @param $in_encoding       
  37.  * @param $out_encoding      
  38.  */ 
  39. function escape($string$in_encoding = 'UTF-8',$out_encoding = 'UCS-2') { 
  40.     $return = ''
  41.     if (function_exists('mb_get_info')) { 
  42.         for($x = 0; $x < mb_strlen ( $string$in_encoding ); $x ++) { 
  43.             $str = mb_substr ( $string$x, 1, $in_encoding ); 
  44.             if (strlen ( $str ) > 1) { // 多字節字符 
  45.                 $return .= '%u' . strtoupper ( bin2hex ( mb_convert_encoding ( $str$out_encoding$in_encoding ) ) ); 
  46.             } else { 
  47.                 $return .= '%' . strtoupper ( bin2hex ( $str ) ); 
  48.             } 
  49.         } 
  50.     } 
  51.     return $return
相關文章
相關標籤/搜索