雅安论坛

标题: 汉字转为ASCII码和ASCII码转换为汉字 [打印本页]

作者: 匿名    时间: 2021-6-16 22:22
标题: 汉字转为ASCII码和ASCII码转换为汉字
字符串转为ASCII
  1. /**
  2. * 字符串转为ASCII
  3. *
  4. * @param string $str 需要转换的字符串
  5. *
  6. * @return string $asc ASCII码
  7. */
  8. function ascii_encode($str)
  9. {
  10.     $str = mb_convert_encoding($str, 'GBK');
  11.     $asc = '';
  12.     for ($i = 0; $i < strlen($str); $i++) {
  13.         $temp_str = dechex(ord($str[$i]));
  14.         $asc .= $temp_str[0].$temp_str[1];
  15.     }
  16.     return strtoupper($asc);
  17. }
复制代码
ASCII转字符串
  1. /**
  2. * ASCII转为字符串
  3. *
  4. * @param string $ascii ascii
  5. *
  6. * @return string $str 字符串
  7. */
  8. function ascii_decode($sacii)
  9. {
  10.     $asc = str_split(strtolower($sacii), 2);
  11.     $str ='';
  12.     for ($i = 0; $i < count($asc); $i++) {
  13.         $str.= chr(hexdec($asc[$i][0].$asc[$i][1]));
  14.     }
  15.     return mb_convert_encoding($str, 'UTF-8', 'GBK');
  16. }
复制代码








欢迎光临 雅安论坛 (https://www.yaanbbs.net/) Powered by Discuz! X3.4