php自定义函数实现汉字转换utf8编码的方法

yipeiwu_com5年前PHP代码库

本文实例讲述了php自定义函数实现汉字转换utf8编码的方法。分享给大家供大家参考,具体如下:

该函数有两部分组成:

function htou($c) {
  $n = (ord($c[0]) & 0x1f) << 12;
  $n += (ord($c[1]) & 0x3f) << 6;
  $n += ord($c[2]) & 0x3f;
  return $n;
}
//在代码中隐藏utf8格式的字符串
function utf8_unicode($str) {
  $encode='';
  for($i=0;$i<strlen($str);$i++) {
    if(ord(substr($str,$i,1))> 0xa0) {
      $encode.='&#'.htou(substr($str,$i,3)).';';
      $i+=2;
    } else {
      $encode.='&#'.ord($str[$i]).';';
    }
  }
  return $encode;
}

我们可以用 utf8_unicode() 就可以转换汉字,返回为汉字的utf8编码。这样输出网页不会是乱码。

PS:这里再为大家推荐几款非常实用的在线编码转换工具供大家参考使用:

UTF-8编码转换工具:
http://tools.jb51.net/transcoding/convutf

在线编码转换工具(utf-8/utf-32/Punycode/Base64):
http://tools.jb51.net/transcoding/decode_encode_tool

Native/UTF-8在线编码转换工具:
http://tools.jb51.net/transcoding/native2utf8

更多关于PHP相关内容感兴趣的读者可查看本站专题:《PHP编码与转码操作技巧汇总》、《php面向对象程序设计入门教程》、《PHP数学运算技巧总结》、《PHP数组(Array)操作技巧大全》、《php字符串(string)用法总结》、《PHP数据结构与算法教程》、《php程序设计算法总结》、《php正则表达式用法总结》、及《php常见数据库操作技巧汇总

希望本文所述对大家PHP程序设计有所帮助。

相关文章

PHP数组操作——获取数组最后一个值的方法

php开发过程中,可能经常需要对取出的数组要获取数组的最后健或值。在这里【宜配屋www.yipeiwu.com】总结了三个方法,并且跟据他们三个方法在一些情况下如何使用的条件限制进行了说...

解决PHP 7编译安装错误:cannot stat ‘phar.phar’: No such file or directory

解决PHP 7编译安装错误:cannot stat ‘phar.phar’: No such file or directory

前言 最近因为工作需要要使用PHP 7,所以从网上找教程进行安装, 结果编译没问题, 安装的时候报了错误。 错误如下 cp -pR -f phar.phar /usr/local/p...

php错误提示failed to open stream: HTTP request failed!的完美解决方法

google或者baidu一下,好多这样的问题,解决的方法都是修改php.ini,把allow_url_fopen给启用,改成 allow_url_fopen = On 这样做可以解决某...

解析php中反射的应用

一  反射的使用: 复制代码 代码如下:<?phpclass Person{ public $name; function __construct($...

PHP开发中的错误收集,不定期更新。

Fatal error: Non-static method Conn::__construct() cannot be called statically in /file.php 没...