今天在做一个网站的功能的时候需要实现字符串(中文汉字)与ASCII互转,这也是一个经常使用的功能,接下来为大家分享一下代码,有需要的小伙伴可以参考一下:

1、将字符串转ASCII:

/*
 * 转换为ascii码
 * $str :字符串或者中文
 */
function strtoascii($str, $prefix="&#") {
    $len = strlen($str);
    $a = 0;
    $scill = '';
    while ($a < $len) {
        $ud = 0;
        if (ord($str{$a}) >= 0 && ord($str{$a}) <= 127) {
            $ud = ord($str{$a});
            $a += 1;
        } else if (ord($str{$a}) >= 192 && ord($str{$a}) <= 223) {
            $ud = (ord($str{$a}) - 192) * 64 + (ord($str{$a + 1}) - 128);
            $a += 2;
        } else if (ord($str{$a}) >= 224 && ord($str{$a}) <= 239) {
            $ud = (ord($str{$a}) - 224) * 4096 + (ord($str{$a + 1}) - 128) * 64 + (ord($str{$a + 2}) - 128);
            $a += 3;
        } else if (ord($str{$a}) >= 240 && ord($str{$a}) <= 247) {
            $ud = (ord($str{$a}) - 240) * 262144 + (ord($str{$a + 1}) - 128) * 4096 + (ord($str{$a + 2}) - 128) * 64 + (ord($str{$a + 3}) - 128);
            $a += 4;
        } else if (ord($str{$a}) >= 248 && ord($str{$a}) <= 251) {
            $ud = (ord($str{$a}) - 248) * 16777216 + (ord($str{$a + 1}) - 128) * 262144 + (ord($str{$a + 2}) - 128) * 4096 + (ord($str{$a + 3}) - 128) * 64 + (ord($str{$a + 4}) - 128);
            $a += 5;
        } else if (ord($str{$a}) >= 252 && ord($str{$a}) <= 253) {
            $ud = (ord($str{$a}) - 252) * 1073741824 + (ord($str{$a + 1}) - 128) * 16777216 + (ord($str{$a + 2}) - 128) * 262144 + (ord($str{$a + 3}) - 128) * 4096 + (ord($str{$a + 4}) - 128) * 64 + (ord($str{$a + 5}) - 128);
            $a += 6;
        } else if (ord($str{$a}) >= 254 && ord($str{$a}) <= 255) { //error
            $ud = false;
        }
        $scill .= $prefix.$ud.";";
    }
    return $scill;
}

2、ascll码转字符串(中文):

/*
 * ascii码转换为字符串(中文)
 * $str :ascii码
 */
function asciitostr($str, $prefix="&#") {
    $str = str_replace($prefix, "", $str);
    $a = explode(";", $str);
    $utf ='';
    foreach ($a as $dec) {
        if ($dec < 128) {
            $utf .= chr($dec);
        } else if ($dec < 2048) {
            $utf .= chr(192 + (($dec - ($dec % 64)) / 64));
            $utf .= chr(128 + ($dec % 64));
        } else {
            $utf .= chr(224 + (($dec - ($dec % 4096)) / 4096));
            $utf .= chr(128 + ((($dec % 4096) - ($dec % 64)) / 64));
            $utf .= chr(128 + ($dec % 64));
        }
    }
    return $utf;
}
声明:本站所有文章,如无特殊说明或标注,均为本站原创发布。任何个人或组织,在未征得本站同意时,禁止复制、盗用、采集、发布本站内容到任何网站、书籍等各类媒体平台。如若本站内容侵犯了原著者的合法权益,可联系我们进行处理。