首頁 >後端開發 >php教程 >PHP ASCII码转换操作类

PHP ASCII码转换操作类

WBOY
WBOY原創
2016-06-20 13:02:451445瀏覽

PHP ASCII码转换操作类

PHP ASCII码转换类可以把中文转ascii码。并且可以批量转换,还增加了一个常用的ascii代码还原字符。

具体代码如下:

<?php<br />class ascii<br />{<br /> <br />function decode($str)<br />{<br />    preg_match_all( "/(d{2,5})/", $str,$a);<br />    $a = $a[0];<br />    foreach ($a as $dec)<br />    {<br />        if ($dec < 128)<br />        {<br />            $utf .= chr($dec);<br />        }<br />        else if ($dec < 2048)<br />       {<br />            $utf .= chr(192 + (($dec - ($dec % 64)) / 64));<br />            $utf .= chr(128 + ($dec % 64));<br />        }<br />        else<br />        {<br />            $utf .= chr(224 + (($dec - ($dec % 4096)) / 4096)); <br />            $utf .= chr(128 + ((($dec % 4096) - ($dec % 64)) / 64)); <br />            $utf .= chr(128 + ($dec % 64)); <br />        } <br />    } <br />    return $utf; <br />}<br /> <br />function encode($c)<br />{ <br />    $len = strlen($c); <br />    $a = 0; <br />    while ($a < $len)<br />    {<br />        $ud = 0; <br />        if (ord($c{$a}) >=0 && ord($c{$a})<=127)<br />        {<br />            $ud = ord($c{$a}); <br />            $a += 1; <br />        }<br />        else if (ord($c{$a}) >=192 && ord($c{$a})<=223)<br />        {<br />            $ud = (ord($c{$a})-192)*64 + (ord($c{$a+1})-128); <br />            $a += 2; <br />        }<br />        else if (ord($c{$a}) >=224 && ord($c{$a})<=239)<br />        {<br />            $ud = (ord($c{$a})-224)*4096 + (ord($c{$a+1})-128)*64 + (ord($c{$a+2})-128); <br />            $a += 3; <br />        }<br />        else if (ord($c{$a}) >=240 && ord($c{$a})<=247)<br />        {<br />            $ud = (ord($c{$a})-240)*262144 + (ord($c{$a+1})-128)*4096 + (ord($c{$a+2})-128)*64 + (ord($c{$a+3})-128); <br />            $a += 4; <br />        }<br />        else if (ord($c{$a}) >=248 && ord($c{$a})<=251)<br />        {<br />            $ud = (ord($c{$a})-248)*16777216 + (ord($c{$a+1})-128)*262144 + (ord($c{$a+2})-128)*4096 + (ord($c{$a+3})-128)*64 + (ord($c{$a+4})-128);<br />            $a += 5; <br />        }<br />        else if (ord($c{$a}) >=252 && ord($c{$a})<=253)<br />        {<br />            $ud = (ord($c{$a})-252)*1073741824 + (ord($c{$a+1})-128)*16777216 + (ord($c{$a+2})-128)*262144 + (ord($c{$a+3})-128)*4096 + (ord($c{$a+4})-128)*64 + (ord($c{$a+5})-128); <br />            $a += 6; <br />        }<br />        else if (ord($c{$a}) >=254 && ord($c{$a})<=255)<br />        { //error<br />            $ud = false; <br />        } <br />        $scill .= "&#$ud;";<br />    } <br />    return $scill; <br />}<br /> <br />}<br />?>


陳述:
本文內容由網友自願投稿,版權歸原作者所有。本站不承擔相應的法律責任。如發現涉嫌抄襲或侵權的內容,請聯絡admin@php.cn