在處理 BIG5 轉換 UTF-8 的過程中,字串還存在一些 HTML entity 需要額外處理。 以下還順便處理缺省分號造成沒有轉換的問題。
function entity2utf8($s) { return preg_replace_callback('|&#\d+;?|', function ($matches) { $match = $matches[0]; if (mb_strpos($match, ';') === false) { $match .= ';'; } return mb_convert_encoding($match, 'UTF-8', 'HTML-ENTITIES'); }, $s); } $s ='英國皇冠♔'; echo entity2utf8($s); // output: 英國皇冠♔
PHP 5.3.24 (cli) (built: Jun 10 2013 16:42:20) Copyright (c) 1997-2013 The PHP Group Zend Engine v2.3.0, Copyright (c) 1998-2013 Zend Technologies with Xdebug v2.2.0rc1, Copyright (c) 2002-2012, by Derick Rethans