PHP实现Javascript中的escape及unescape函数代码分享
php  /  管理员 发布于 7年前   277
这个类相当好用.作用么,PHP做JSON传递GBK字符,比如中文,日文,韩文神马的Unicode最合适不过了.. google code 上找到的另外一个类似脚本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); } }?>
=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})|.{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)=="") $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); } ?>
您可能感兴趣的文章:
122 在
学历:一种延缓就业设计,生活需求下的权衡之选中评论 工作几年后,报名考研了,到现在还没认真学习备考,迷茫中。作为一名北漂互联网打工人..123 在
Clash for Windows作者删库跑路了,github已404中评论 按理说只要你在国内,所有的流量进出都在监控范围内,不管你怎么隐藏也没用,想搞你分..原梓番博客 在
在Laravel框架中使用模型Model分表最简单的方法中评论 好久好久都没看友情链接申请了,今天刚看,已经添加。..博主 在
佛跳墙vpn软件不会用?上不了网?佛跳墙vpn常见问题以及解决办法中评论 @1111老铁这个不行了,可以看看近期评论的其他文章..1111 在
佛跳墙vpn软件不会用?上不了网?佛跳墙vpn常见问题以及解决办法中评论 网站不能打开,博主百忙中能否发个APP下载链接,佛跳墙或极光..
Copyright·© 2019 侯体宗版权所有·
粤ICP备20027696号