欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页  >  后端开发

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

程序员文章站 2022-05-19 19:09:28
...
这个类相当好用.作用么,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])$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);
    }
 
?>