onnov / detect-encoding
文本编码定义类,代替 mb_detect_encoding。定义:utf-8, windows-1251, koi8-r, iso-8859-5, ibm866, .....
v2.0.0
2021-01-04 14:29 UTC
Requires
- php: >=7.3
- ext-iconv: *
README
检测编码
基于一系列代码页字符数的文本编码定义类。
截至目前,在 PHP v7.* 中,mb_detect_encoding
函数表现不佳。因此,你需要以某种方式解决这个问题。这个类是一个解决方案。
内置编码和准确性
MacCyrillic 的准确性最差,你需要至少 60 个字符才能以 92.15% 的准确性确定这种编码。Windows-1251 编码的准确性也非常差。这是因为它们在表中的字符数量重叠非常严重。
幸运的是,MacCyrillic 和 ibm866 编码不用于网页编码。默认情况下,它们在脚本中是禁用的,但如有必要,你可以启用它们。
即使在 5 到 10 个字母的短句中,确定准确性也很高。对于 60 个字母的短语,确定准确性达到 100%。
确定编码非常快,例如,在 0.00096 秒内检查超过 1,300,000 个西里尔字符的文本。(在我的计算机上)
相关链接:http://patttern.blogspot.com/2012/07/php-python.html
安装
Composer(推荐)使用 Composer 从 Packagist 安装此库:onnov/captcha
从您的项目目录运行以下命令以添加依赖项
composer require onnov/detect-encoding
或者,直接在 composer.json 文件中添加依赖项
{ "require": { "onnov/detect-encoding": "^1.0" } }
项目中的类是根据 PSR-4 标准 structured 的,因此您也可以使用自己的自动加载器或直接在代码中 require 所需的文件。
使用方法
use Onnov\DetectEncoding\EncodingDetector; $detector = new EncodingDetector();
- 文本编码定义
use Onnov\DetectEncoding\EncodingDetector; $detector = new EncodingDetector(); $text = 'Проверяемый текст'; $detector->getEncoding($text);
- 将未知编码的文本转换为指定编码的方法,默认为 utf-8,可选参数
use Onnov\DetectEncoding\EncodingDetector; $detector = new EncodingDetector(); /** * Method for converting text of an unknown encoding into a given encoding, by default in utf-8 * optional parameters: * $extra = '//TRANSLIT' (default setting) , other options: '' or '//IGNORE' * $encoding = 'utf-8' (default setting) , other options: any encoding that is available iconv * * @param string $text * @param string $extra * @param string $encoding * * @return string * @throws RuntimeException */ $detector->iconvXtoEncoding($text);
- 启用编码定义的方法
use Onnov\DetectEncoding\EncodingDetector; $detector = new EncodingDetector(); $detector->enableEncoding([ EncodingDetector::IBM866, EncodingDetector::MAC_CYRILLIC, ]);
- 禁用编码定义的方法
use Onnov\DetectEncoding\EncodingDetector; $detector = new EncodingDetector(); $detector->disableEncoding([ EncodingDetector::ISO_8859_5, ]);
- 添加自定义编码的方法
use Onnov\DetectEncoding\EncodingDetector; $detector = new EncodingDetector(); $detector->addEncoding([ 'encodingName' => [ 'upper' => '1-50,200-250,253', // uppercase character number range 'lower' => '55-100,120-180,199', // lowercase character number range ], ]);
- 获取自定义编码范围的方法
use Onnov\DetectEncoding\CodePage; // utf-8 encoded alphabet $cyrillicUppercase = 'АБВГДЕЁЖЗИЙКЛМНОПРСТУФЧЦЧШЩЪЫЬЭЮЯ'; $cyrillicLowercase = 'абвгдеёжзийклмнопрстуфхцчшщъыьэюя'; $codePage = new CodePage(); $encodingRange = $codePage->getRange($cyrillicUppercase, $cyrillicLowercase, 'koi8-u');
Symfony 使用
添加到 services.yaml 文件
services: Onnov\DetectEncoding\EncodingDetector: autowire: true