天天看点

字符串与ascii的转换

 字符串中只能包含字符,特殊符号不行。

//字符串转化为ascii

字符串与ascii的转换

function  str2asc( $str )

字符串与ascii的转换

{

字符串与ascii的转换

     $num = '' ;

字符串与ascii的转换

     while ( strlen ( $str ) != 0 )

字符串与ascii的转换

    {

字符串与ascii的转换

         $a = substr ( $str , 0 , 1 );

字符串与ascii的转换

         $num .= ord ( $a );

字符串与ascii的转换

         $str = substr ( $str , 1 , strlen ( $str ));

字符串与ascii的转换

    }

字符串与ascii的转换

     return   $num ;

字符串与ascii的转换

}

//ascii转化为字符串

字符串与ascii的转换

function  asc2str( $num )

字符串与ascii的转换

{

字符串与ascii的转换

     $num = ( string ) $num ;

字符串与ascii的转换

     $str = '' ;

字符串与ascii的转换

     while ( strlen ( $num ) != 0 )

字符串与ascii的转换

    {

字符串与ascii的转换

         $a = (int) substr ( $num , 0 , 1 );

字符串与ascii的转换

         if ( $a > 2 )

字符串与ascii的转换

        {

字符串与ascii的转换

             $b = (int) substr ( $num , 0 , 2 );

字符串与ascii的转换

             $num = substr ( $num , 2 , strlen ( $num ));

字符串与ascii的转换

        } else

字符串与ascii的转换

        {

字符串与ascii的转换

             $b = (int) substr ( $num , 0 , 3 );

字符串与ascii的转换

             $num = substr ( $num , 3 , strlen ( $num ));

字符串与ascii的转换

        }

字符串与ascii的转换

         $str .= chr ( $b );

字符串与ascii的转换

    }

字符串与ascii的转换

     return   $str ;

字符串与ascii的转换

}

示例:

echo str2asc( 'sfdsl ');

echo  ' <br > ';

echo asc2str(str2asc( 'sfdsl '));

---------------------

115102100115108

sfdsl 

注:调用asc2str( '123456 ') 不能asc2str(123456) ,也就是要将123456转化为字符串。