javascript
最完整的phpescape函数
function phpescape($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",$v));
if (!eregi("WIN",PHP_OS)){
$tmpString = substr($tmpString,2,2).substr($tmpString,0,2);
}
$reString.="%u".$tmpString;
} else {
$reString.= rawurlencode($v);
}
}
return $reString;
}
//该方法在某些linux系统下
//会因为iconv的php版本问题
//造成该函数方法无法正常使用
//使用前请测试先
function phpescape($str) {
preg_match_all("/[€-ÿ].|[-]+/",$str,$r);
$ar = $r[0];
foreach($ar as $k=>$v) {
if(ord($v[0]) < 128){
$ar[$k] = rawurlencode($v);
echo $ar[$k]."<BR>";
}
else {
$ar[$k] = "%u".bin2hex(iconv("GBK","ISO-10646-UCS-2",$v)); //此处GBK为目标代码的编码格式请实际情况修改
echo $ar[$k]."<BR>";
}
}
return join("",$ar);
}
//该方法为上面的改进版
//首先判断平台版本是否为win系统
//但该版本会有些特殊字符无法使用
function phpescape($str){
$sublen=strlen($str);
$reString="";
for ($i=0;$i<$sublen;$i++){
if(ord($str[$i])>=127){
$tmpString=bin2hex(iconv("GBK","ucs-2",substr($str,$i,2))); //此处GBK为目标代码的编码格式请实际情况修改
if (!eregi("WIN",PHP_OS)){
$tmpString=substr($tmpString,2,2).substr($tmpString,0,2);
}
$reString.="%u".$tmpString;
$i++;
} else {
$reString.="%".dechex(ord($str[$i]));
}
}
return $reString;
}
function unescape($str) {
$str = rawurldecode($str);
preg_match_all("/%u.{4}|.{4};|d+;|.+/U",$str,$r);
$ar = $r[0];
foreach($ar as $k=>$v) {
if(substr($v,0,2) == "%u")
$ar[$k] = iconv("UCS-2","GBK",pack("H4",substr($v,-4)));
elseif(substr($v,0,3) == "")
$ar[$k] = iconv("UCS-2","GBK",pack("H4",substr($v,3,-1)));
elseif(substr($v,0,2) == "") {
$ar[$k] = iconv("UCS-2","GBK",pack("n",substr($v,2,-1)));
}
}
return join("",$ar);
}