php实现JavaScript中的escape和unescape函数

作者: admin 分类: php 发布时间: 2013-05-18 08:20

php实现JavaScript中的escape和unescape函数

function js_escape($str,$inputcharset='utf-8'){
	if($inputcharset=='utf-8')
		$str=iconv('utf-8','gbk',$str);
	 $sublen=strlen($str);
	 $retrunString="";
	 for ($i=0;$i<$sublen;$i++){
		if(ord($str[$i])>=127){
		   $tmpString=bin2hex(iconv("gb2312","ucs-2",substr($str,$i,2)));
		   //$tmpString=substr($tmpString,2,2).substr($tmpString,0,2);//window下可能要打开此项
		   $retrunString.="%u".$tmpString;
		   $i++;
		 } else {
			$retrunString.="%".dechex(ord($str[$i]));
		}
	 }
	 return $retrunString;
}

function js_unescape($str,$outputcharset='utf-8'){
	$ret = '';
	$len = strlen($str);
	for ($i = 0; $i < $len; $i++){
		if ($str[$i] == '%' && $str[$i+1] == 'u'){
			$val = hexdec(substr($str, $i+2, 4));
			if ($val < 0x7f) $ret .= chr($val);
			else if($val < 0x800) $ret .= chr(0xc0|($val>>6)).chr(0x80|($val&0x3f));
			else $ret .= chr(0xe0|($val>>12)).chr(0x80|(($val>>6)&0x3f)).chr(0x80|($val&0x3f));
			$i += 5;
		}
		else if ($str[$i] == '%'){
			$ret .= urldecode(substr($str, $i, 3));
			$i += 2;
		}
		else
			$ret .= $str[$i];
	}
	return ($outputcharset=='utf-8')? $ret:iconv('utf-8','gbk',$ret);;
}