tohokuaikiのチラシの裏

技術的ネタとか。

生のUnicode文字をHTMLエンティティにする。

UTF-8一辺倒な最近は問題ないのですが、たまにレガシーな環境に行くとUnicode文字が出なくて困ります。

で、HTMLエンティティがあるものはそっちにしてしまおうという関数。

<?php
    function escapeUnicodeCharacter($html)
    {
        static $unicode_table ;
        
        if (is_null($unicode_table)){
            $unicode_table = array(
                'before' => array(),
                'after'  => array(),
                );
            // #h-24.2.1
            $j = range(160, 255);
            // #h-24.3.1
            $j = array_merge($j, range(913, 969));
            $j = array_merge($j, array(401, 977, 978, 982, 8226, 8230, 8242, 8243, 8254, 8260, 8465, 8472, 8476, 8482, 8501, 8592, 8593, 8594, 8595, 8596, 8629, 8656, 8657, 8658, 8659, 8660, 8704, 8706, 8707, 8709, 8711, 8712, 8713, 8715, 8719, 8721, 8722, 8727, 8730, 8733, 8734, 8736, 8743, 8744, 8745, 8746, 8747, 8756, 8764, 8773, 8776, 8800, 8801, 8804, 8805, 8834, 8835, 8836, 8838, 8839, 8853, 8855, 8869, 8901, 8968, 8969, 8970, 8971, 9001, 9002, 9674, 9824, 9827, 9829, 9830));
            // #h-24.4.1
            $j = array_merge($j, array(/*34, 38, 60, 62,*/ 338, 339, 352, 353, 376, 710, 732, 8194, 8195, 8201, 8204, 8205, 8206, 8207, 8211, 8212, 8216, 8217, 8218, 8220, 8221, 8222, 8224, 8225, 8240, 8249, 8250, 8364));
            
            foreach ($j as $i){
                $entity = sprintf('&#%s;', $i);
                $unicode_table['before'][] = html_entity_decode($entity, ENT_NOQUOTES, 'UTF-8');
                $unicode_table['after'][]  = $entity;
            }
        }
        
        return str_replace($unicode_table['before'], $unicode_table['after'], $html);
    }

有効なHTMLエンティティはW3Cのページから取得。
34, 38, 60, 62
については、コントロールコードなので(<>”&)外す。