栏目分类:
子分类:
返回
名师互学网用户登录
快速导航关闭
当前搜索
当前分类
子分类
实用工具
热门搜索
名师互学网 > IT > 软件开发 > 后端开发 > PHP

PHP实现Javascript中的escape及unescape函数代码分享

PHP 更新时间: 发布时间: IT归档 最新发布 模块sitemap 名妆网 法律咨询 聚返吧 英语巴士网 伯小乐 网商动力

PHP实现Javascript中的escape及unescape函数代码分享

这个类相当好用.作用么,PHP做JSON传递GBK字符,比如中文,日文,韩文神马的Unicode最合适不过了..

1){// 多字节字符 
 $return.='%u'.strtoupper(bin2hex(mb_convert_encoding($str,'UCS-2',$encoding)));
      }else{
 $return.='%'.strtoupper(bin2hex($str));
      }
    }
    return$return;
  }
  
  functiongb2utf8($string,$encoding='utf-8',$from_encode='gb2312')
  {
    returnmb_convert_encoding($string,$encoding,$from_encode);
  }
  
}
?>

google code 上找到的另外一个类似脚本

=127)
     {
  $tmpString=bin2hex(iconv("gbk","ucs-2",substr($str,$i,2)));
  $tmpString=substr($tmpString,2,2).substr($tmpString,0,2);
  $retrunString.="%u".$tmpString;
  $i++;
     }else{
  $retrunString.="%".dechex(ord($str[$i]));
     }
 }
 return$retrunString;
    }
 
 
    functionescape($str)
    {
 preg_match_all("/[x80-xff].|[x01-x7f]+/",$str,$r);
 $ar=$r[0];
 foreach($aras$k=>$v)
 {
     if(ord($v[0])<128)
  $ar[$k]=rawurlencode($v);
     else
  $ar[$k]="%u".bin2hex(iconv("UTF-8","UCS-2",$v));
 }
 returnjoin("",$ar);
    }
 
    functionphpunescape($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;
    }
    
    
    functionunescape($str)
    {
 $str=rawurldecode($str);
 preg_match_all("/(?:%u.{4})|&#x.{4};|&#d+;|.+/U",$str,$r);
 $ar=$r[0];
 #print_r($ar);
 foreach($aras$k=>$v)
 {
     if(substr($v,0,2)=="%u")
  $ar[$k]=iconv("UCS-2","UTF-8",pack("H4",substr($v,-4)));
     elseif(substr($v,0,3)=="&#x")
  $ar[$k]=iconv("UCS-2","UTF-8",pack("H4",substr($v,3,-1)));
     elseif(substr($v,0,2)=="&#")
     {
  //echo substr($v,2,-1)."";
  $ar[$k]=iconv("UCS-2","UTF-8",pack("n",substr($v,2,-1)));
     }
 }
 returnjoin("",$ar);
    }
 
?>

转载请注明:文章转载自 www.mshxw.com
本文地址:https://www.mshxw.com/it/46261.html
我们一直用心在做
关于我们 文章归档 网站地图 联系我们

版权所有 (c)2021-2022 MSHXW.COM

ICP备案号:晋ICP备2021003244-6号