ITPub博客

首页 > 应用开发 > IT综合 > PHP版的escape、unescape函数

PHP版的escape、unescape函数

原创 IT综合 作者:jyb2014 时间:2014-10-27 16:16:41 0 删除 编辑
//编码,编码后为小写
function escape($str){
preg_match_all("/[\x80-\xff].|[\x01-\x7f]+/",$str,$newstr);
$ar = $newstr[0];
foreach($ar as $k=>$v){
   if(ord($ar[$k])>=127){
    $tmpString=bin2hex(iconv("GBK","ucs-2//IGNORE",$v));
    if (!eregi("WIN",PHP_OS)){
     $tmpString = substr($tmpString,2,2).substr($tmpString,0,2);
    }
    $reString.="%u".$tmpString;
   }else{
    $reString.= rawurlencode($v);
   }
}
return $reString;
}


//解码为HTML实体字符
function unescape ($source){ 
$decodedStr = ""; 
$pos = 0; 
$len = strlen ($source); 
while ($pos < $len){ 
   $charAt = substr ($source, $pos, 1); 
         if ($charAt == '%'){ 
    $pos++; 
    $charAt = substr ($source, $pos, 1); 
             if ($charAt == 'u'){ 
     // we got a unicode character 
     $pos++; 
     $unicodeHexVal = substr ($source, $pos, 4); 
     $unicode = hexdec ($unicodeHexVal); 
     $entity = "&#". $unicode . ';'; 
     $decodedStr .= utf8_encode ($entity); 
     $pos += 4; 
             }else{ 
     // we have an escaped ascii character 
     $hexVal = substr ($source, $pos, 2); 
     $decodedStr .= chr (hexdec ($hexVal)); 
     $pos += 2; 
    } 
   }else{ 
    $decodedStr .= $charAt; 
    $pos++; 
   } 
} 
return $decodedStr; 
}




//直接解码为字符串。网上找到的这个版本的函数是解码为HTML实体字符,这是我修改的
function unescape($source){ 
$decodedStr = ""; 
$pos = 0; 
$len = strlen ($source); 
while ($pos < $len){ 
   $charAt = substr ($source, $pos, 1); 
         if ($charAt == '%'){ 
    $pos++; 
    $charAt = substr ($source, $pos, 1); 
             if ($charAt == 'u'){ 
     // we got a unicode character 
     $pos++; 
     $unicodeHexVal = substr ($source, $pos, 4); 
     $unicode = hexdec ($unicodeHexVal); 
     $decodedStr .= u2utf82gb($unicode); 
     $pos += 4; 
             }else{ 
     // we have an escaped ascii character 
     $hexVal = substr ($source, $pos, 2); 
     $decodedStr .= chr (hexdec ($hexVal)); 
     $pos += 2; 
    } 
   }else{ 
    $decodedStr .= $charAt; 
    $pos++; 
   } 
} 
return $decodedStr; 
}
function u2utf82gb($c){
$strphp = "";
if($c < 0x80){
   $strphp .= $c;
}elseif($c < 0x800){
   $strphp .= chr(0xC0 | $c>>6);
   $strphp .= chr(0x80 | $c & 0x3F);
}elseif($c < 0x10000){
   $strphp .= chr(0xE0 | $c>>12);
   $strphp .= chr(0x80 | $c>>6 & 0x3F);
   $strphp .= chr(0x80 | $c & 0x3F);
}elseif($c < 0x200000){
   $strphp .= chr(0xF0 | $c>>18);
   $strphp .= chr(0x80 | $c>>12 & 0x3F);
   $strphp .= chr(0x80 | $c>>6 & 0x3F);
   $strphp .= chr(0x80 | $c & 0x3F);
}
return iconv('UTF-8', 'GB2312', $strphp);
}

来自 “ ITPUB博客 ” ,链接:https://blog.itpub.net/29753604/viewspace-1310863/ ,如需转载,请注明出处,否则将追究法律责任。

请登录后发表评论 登录
全部评论

注册时间:2014-07-15

  • 博文量
    101
  • 访问量
    196521