Home  >  Article  >  Backend Development  >  PHP ASCII码转换操作类

PHP ASCII码转换操作类

WBOY
WBOYOriginal
2016-06-20 13:02:451388browse

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 />?>


Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn