serverdensity/mendedstring

此包已被废弃,不再维护。没有建议的替代包。

用于检测包含单字节编码UTF8字符的Unicode字符串的库

1.1.0 2013-01-02 22:00 UTC

This package is not auto-updated.

Last update: 2024-07-06 13:59:13 UTC


README

serverdensity/mendedstring

MendedString 是一个PHP类,用于检测包含单字节编码UTF-8字符的Unicode字符串,例如使用PHP的 utf8_encode() 函数在包含非ASCII字符的字符串上,然后保存到支持全UTF-8编码的数据源(如MongoDB)中创建的字符串。

Build Status

用例

由于我们依赖旧代码中的PHP utf8_encodeutf8_decode 内置函数,因此我们创建了 MendedString。每次我们将用户数据保存到我们的数据存储(在这种情况下是MongoDB)时,我们首先需要使用 utf8_encode() 进行编码,并记住在将输出返回给用户时使用 utf8_decode()

在PHP和浏览器中设置正确的编码后,这不应该有必要,因为MongoDB中的字符串存储在BSON文档格式中,它使用UTF-8,这不应该必要。在我们将代码迁移到使用正确的编码时,我们发现我们存储在Mongo中的大量数据已经使用单字节包装多字节字符(通过 utf8_encode)进行包装,为了能够丢弃所有这样的包装,我们需要首先迁移现有数据。

MendedString 通过检查这些字符并适当地解码它们来实现这一点,如果需要,可以多次进行,直到您拥有一个使用Unicode编码的本地PHP字符串。

注意:它不使用 mb_detect_encoding 或类似的多字节扩展,因为我们发现这在使用单字节包装字符进行检测时不可靠,只检测实际的多字节字符,这对我们的目的毫无用处。

安装

如果您正在使用 Composer 进行您的项目,您只需将 serverdensity/mendedstring 添加到您的需求中。

否则,您需要将 mendedstring/src/ServerDensity/MendedString.php 包含/要求在您的代码中。

使用

要修复包含Unicode字符的损坏(或可能损坏)的字符串,只需将字符串传递给一个新的 \ServerDensity\MendedString\MendedString 实例。每个实例都是不可变的,因此要修复新的字符串,您需要创建一个新的实例,例如。

use \ServerDensity\MendedString\MendedString;
// The MendedString class exists in the MendedString module to make autoloading
// a bit more efficient.

$broken = utf8_encode('hello world' . utf8_encode('«ταБЬℓσ»'));
$mended = new MendedString($broken);

// Mended strings are lazy-converted, you either have to call ->getConverted()
// or use it as a string (e.g. cast it, concat it with another string etc.) like so:
echo (string)$mended;

许可

MendedString 是BSD许可,您可以自由使用和滥用,但请保留 LICENSE 文件完整。