2

为了避免“怪物字符”,我选择Unicode NCR 形式将非英文字符存储在数据库(MySQL)中。然而,我使用的 PDF 插件 (FPDF) 不接受 Unicode NCR 格式作为正确格式;它直接显示数据,如:

這個一個例子

但我希望它显示如下:

这个例子

有什么方法可以将 Unicode NCR 形式转换为其原始形式?

ps这句话的意思是“这是一个例子”的繁体中文。

ps 我知道 NCR 格式会浪费存储空间,但存储非英文字符是最安全的方法。如果我错了,请纠正我。谢谢。

4

3 回答 3

3

有一个更简单的解决方案,使用 PHP mbstring 扩展。

// convert any Decimal NCRs to Unicode characters
$string = "這個一個例子";
$output = preg_replace_callback(
  '/(&#[0-9]+;)/u', 
  function($m){
    return utf8_entity_decode($m[1]);
  }, 
  $string
);
echo $output; // 這個一個例子

//callback function for the regex
function utf8_entity_decode($entity){
  $convmap = array(0x0, 0x10000, 0, 0xfffff);
  return mb_decode_numericentity($entity, $convmap, 'UTF-8');
}

'utf8_entity_decode' 函数来自 PHP.net (Andrew Simpson):http ://php.net/manual/ru/function.mb-decode-numericentity.php#48085 。我稍微修改了代码以避免正则表达式中不推荐使用的“e”修饰符。

于 2016-07-02T11:57:20.197 回答
1

解决方案非常复杂。

解决方案分为 3 部分: 第 1 部分:安装 FPDF 中文插件 第 2 部分:将 NCR 格式转换为 UTF-8 第 3 部分:将 UTF-8 格式转换为 BIG5(或任何目标编码)

第1部分

我从这里获取了 FPDF 中文插件:http ://dev.xoofoo.org/modules/content/d1/d6e/a00073.html 用于在 FPDF 中显示汉字,并获取所有需要的中文字体。要安装此插件,只需将其包含在 PHP 中即可。(但就我而言,我使用了另一个名为 CellPDF 的插件,它与这个中文插件一起崩溃;因此,我必须合并代码并解决冲突)

第2部分

要将 NCR 格式转换为 UTF-8,我使用以下代码:

function html_entity_decode_utf8($string)
{
    static $trans_tbl;

    // replace numeric entities
    $string = preg_replace('~&#x([0-9a-f]+);~ei', 'code2utf(hexdec("\\1"))', $string);
    $string = preg_replace('~&#([0-9]+);~e', 'code2utf(\\1)', $string);

    // replace literal entities
    if (!isset($trans_tbl))
    {
        $trans_tbl = array();

        foreach (get_html_translation_table(HTML_ENTITIES) as $val=>$key)
            $trans_tbl[$key] = utf8_encode($val);
    }

    return strtr($string, $trans_tbl);
}
function code2utf($num)
{
    if ($num < 128) return chr($num);
    if ($num < 2048) return chr(($num >> 6) + 192) . chr(($num & 63) + 128);
    if ($num < 65536) return chr(($num >> 12) + 224) . chr((($num >> 6) & 63) + 128) . chr(($num & 63) + 128);
    if ($num < 2097152) return chr(($num >> 18) + 240) . chr((($num >> 12) & 63) + 128) . chr((($num >> 6) & 63) + 128) . chr(($num & 63) + 128);
    return '';
}

由 php.net 的 laurynas butkus 编写(链接:http ://www.php.net/manual/en/function.html-entity-decode.php )虽然这段代码本身将 NCR 格式转换为“怪物字符” “,我知道这是一个好的开始。

第 3 部分

在我深入 php.net 之后,我发现了一个不错的函数:iconv,用于转换编码。所以我用以下函数包装了上面的代码:

function ncr_decode($string, $target_encoding='BIG5') {
    return iconv('UTF-8', 'BIG5', html_entity_decode_utf8($string));
}

因此,如果我想转换上一行 NCR 字符串,我只需要运行这个函数:

ncr_decode("&#36889;&#20491;&#19968;&#20491;&#20363;&#23376;");

ps 默认情况下,我将目标编码设置为BIG5。

就是这样!

于 2009-10-21T03:23:02.460 回答
0

看看html_entity_decode

PS:更好的方法是一直使用 UTF-8。在 SO 上搜索有关 PHP、MySQL 和 UTF-8 的问题,其中有一些列出了可能的问题。

于 2009-10-20T07:55:30.877 回答