3

私は単純なクラスでいくつかのメソッドを使用してきましたが、それらはうまく機能しましたがstrtr()、大量の翻訳が定義されているため、それらが非常に遅いことに気付きました。また、非常に長いため、保守と理解がより困難です。

とはいえ、「悪い」例はすべて、文字列を UTF8 に変換するという実際の問題に対する解決策です。

これを行うためのよく知られている、またはより効率的な手段があることを誰か教えてもらえますか? (はい、私はhtmlentities()メソッドとメソッドを試しましたiconv()が、実際にはすべてのファンキーな文字を正しく置き換えていません.

現在使用しているクラスは次のとおりです: https://gist.github.com/2559140

4

1 に答える 1

2

PHP 5.4.0 以降、mbstring のサポートはデフォルトで有効になっています (ただし、ロードされていません)。拡張機能をロードすると、次のことが可能になります。

<? //PHP 5.4+
$ensureIsUTF8 = static function($data){
    $dataEncoding = \mb_detect_encoding(
        $data,
        ['UTF-8', 'windows-1251', 'iso-8859-1', /*others you encounter*/],
        true
    );

    //UTF-16/32 encoding detection always fails for PHP <= 5.4.1
    //Use detection code copied from PHP docs comments:
    //http://www.php.net/manual/en/function.mb-detect-encoding.php
    if ($dataEncoding === false){

        $UTF32_BIG_ENDIAN_BOM = chr(0x00) . chr(0x00) . chr(0xFE) . chr(0xFF);
        $UTF32_LITTLE_ENDIAN_BOM = chr(0xFF) . chr(0xFE) . chr(0x00) . chr(0x00);
        $UTF16_BIG_ENDIAN_BOM = chr(0xFE) . chr(0xFF);
        $UTF16_LITTLE_ENDIAN_BOM = chr(0xFF) . chr(0xFE);

        $first2 = \substr($data, 0, 2);
        $first4 = \substr($data, 0, 4);

        if ($first4 === $UTF32_BIG_ENDIAN_BOM) {
            $dataEncoding = 'UTF-32BE';
        } elseif ($first4 === $UTF32_LITTLE_ENDIAN_BOM) {
            $dataEncoding = 'UTF-32LE';
        } elseif ($first2 === $UTF16_BIG_ENDIAN_BOM) {
            $dataEncoding = 'UTF-16BE';
        } elseif ($first2 === $UTF16_LITTLE_ENDIAN_BOM) {
            $dataEncoding = 'UTF-16LE';
        } else {
            throw new \Exception('Whoa! No idea what that was.');
        }
    }

    if ($dataEncoding === 'UTF-8'){
        return $data;
    } else {
        return \mb_convert_encoding(
           $data,
           'UTF-8',
           $dataEncoding
        );      
    }
};

$utf8Data = $ensureIsUTF8(\file_get_contents('something'));
$utf8Data = $ensureIsUTF8(\file_get_contents('http://somethingElse'));
$utf8Data = $ensureIsUTF8($userProvidedData);
?>
于 2012-05-03T04:14:29.690 に答える