mysql unescape解码_PHP版的escape、unescape函数

这篇博客介绍了如何使用PHP编写`escape`和`unescape`函数,用于MySQL的字符串编码和解码。`escape`函数将字符串转换为小写并进行编码,而`unescape`函数则能解码编码后的字符串,包括处理Unicode字符。文章还提供了一个修改后的`unescape`版本,直接将解码结果转化为字符串而非HTML实体字符。
摘要由CSDN通过智能技术生成

//编码,编码后为小写

function escape($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//IGNORE",$v));

if (!eregi("WIN",PHP_OS)){

$tmpString = substr($tmpString,2,2).substr($tmpString,0,2);

}

$reString.="%u".$tmpString;

}else{

$reString.= rawurlencode($v);

}

}

return $reString;

}

//解码为HTML实体字符

function unescape ($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;

}

//直接解码为字符串。网上找到的这个版本的函数是解码为HTML实体字符,这是我修改的

function unescape($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);

$decodedStr .= u2utf82gb($unicode);

$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;

}

function u2utf82gb($c){

$strphp = "";

if($c < 0x80){

$strphp .= $c;

}elseif($c < 0x800){

$strphp .= chr(0xC0 | $c>>6);

$strphp .= chr(0x80 | $c & 0x3F);

}elseif($c < 0x10000){

$strphp .= chr(0xE0 | $c>>12);

$strphp .= chr(0x80 | $c>>6 & 0x3F);

$strphp .= chr(0x80 | $c & 0x3F);

}elseif($c < 0x200000){

$strphp .= chr(0xF0 | $c>>18);

$strphp .= chr(0x80 | $c>>12 & 0x3F);

$strphp .= chr(0x80 | $c>>6 & 0x3F);

$strphp .= chr(0x80 | $c & 0x3F);

}

return iconv('UTF-8', 'GB2312', $strphp);

}

来自 “ ITPUB博客 ” ,链接:http://blog.itpub.net/29753604/viewspace-1310863/,如需转载,请注明出处,否则将追究法律责任。

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值