php自动识别文字编码并转换为目标编码的方法_PHP
May 30, 2016 am 08:47 AM
php
Automatic Identification
Convert
本文实例讲述了php自动识别文字编码并转换为目标编码的方法。分享给大家供大家参考。具体如下:
在PHP处理页面的时候,我们对于字符集的转换都是采用了iconv或者mb_convert等函数,但,这其实是有一个前提的。即我们事先得知道in和out是什么样的编码,我们才能进行正确的转换。
虽然大多数转换都是在gbk和utf-8之间转,但如果不知道转换对象的编码怎么办呢?谷歌出来这么一个函数safeEncoding,可以简单的识别UTF8和GBK的编码。这个函数在一定程度上识别的很准确,但是在一些比较复杂的环境中就不是那么的好用了. 下面我结合了GBK和UTF-8编码的不同点,使用正则表达式来判断UTF-8编码并使用mb_convert_encoding函数来进行转换. 在国内,基本上比较流行的编码就是GBK和UTF-8, 所以这个函数是针对这两个编码进行自动转换的.
/** * @ string 需要转换的文字 * @ encoding 目标编码 **/ function detect_encoding($string,$encoding = 'gbk'){ $is_utf8 = preg_match('%^(?:[\x09\x0A\x0D\x20-\x7E]| [\xC2-\xDF][\x80-\xBF]| \xE0[\xA0-\xBF][\x80-\xBF] | [\xE1-\xEC\xEE\xEF][\x80-\xBF]{2} | \xED[\x80-\x9F][\x80-\xBF] | \xF0[\x90-\xBF][\x80-\xBF]{2} | [\xF1-\xF3][\x80-\xBF]{3} | \xF4[\x80-\x8F][\x80-\xBF]{2} )*$%xs', $string); if($is_utf8 && $encoding == 'utf8'){ return $string; }elseif($is_utf8){ return mb_convert_encoding($string, $encoding, "UTF-8"); }else{ return mb_convert_encoding($string, $encoding, 'gbk,gb2312,big5'); } }
Copy after login
希望本文所述对大家的php程序设计有所帮助。
Statement of this Website
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

Hot Article
How Long Does It Take To Beat Split Fiction?
3 weeks ago
By DDD
Repo: How To Revive Teammates
3 weeks ago
By 尊渡假赌尊渡假赌尊渡假赌
Hello Kitty Island Adventure: How To Get Giant Seeds
3 weeks ago
By 尊渡假赌尊渡假赌尊渡假赌
R.E.P.O. Energy Crystals Explained and What They Do (Yellow Crystal)
1 weeks ago
By 尊渡假赌尊渡假赌尊渡假赌

Hot tools Tags

Hot Article
How Long Does It Take To Beat Split Fiction?
3 weeks ago
By DDD
Repo: How To Revive Teammates
3 weeks ago
By 尊渡假赌尊渡假赌尊渡假赌
Hello Kitty Island Adventure: How To Get Giant Seeds
3 weeks ago
By 尊渡假赌尊渡假赌尊渡假赌
R.E.P.O. Energy Crystals Explained and What They Do (Yellow Crystal)
1 weeks ago
By 尊渡假赌尊渡假赌尊渡假赌

Hot Article Tags

Notepad++7.3.1
Easy-to-use and free code editor

SublimeText3 Chinese version
Chinese version, very easy to use

Zend Studio 13.0.1
Powerful PHP integrated development environment

Dreamweaver CS6
Visual web development tools

SublimeText3 Mac version
God-level code editing software (SublimeText3)

Hot Topics

PHP 8.4 Installation and Upgrade guide for Ubuntu and Debian

How To Set Up Visual Studio Code (VS Code) for PHP Development
