php - 在 PHP 中将 utf8 转换为 latin1。所有大于 255 的字符都转换为 char 引用

标签 php character-encoding

我需要将 UTF-8 格式的文本转换为 ISO-8859-1 编码的文本,这样任何不属于 ISO-8859-1 集的字符都会变成字符引用。 (例如 β)

例子:我想把文字变成这样

hello é β 水

进入

hello é β 水

我正在用 PHP 完成所有这些工作。我尝试了内置函数、iconv 和 tidy 以及它们的组合,但仍然无法获得可靠的解决方案。

这是我目前的情况

// convert any characters fount in the entity table into HTML entities
// do not double encode entities, do not mess with quotes
// use UTF-8 as character encoding because the page submits UTF-8
$str = htmlentities($str,ENT_NOQUOTES,'UTF-8',false);
//print $str."\n";

// convert text from UTF-8 to ISO-8859-1, 
// characters that cannot be converted will be converted to ?
$str = utf8_decode($str);
//print $str."\n";    

// make string XML valid.
// mainly it converts text entities into numeric entities.
$opts = array(  "output-xhtml"      => true, 
            "output-xml"        => true, 
            "show-body-only"    => true,
            "numeric-entities"  => true,
            "wrap"              => 0,
            "indent"            => false,
            "char-encoding" => 'latin1'
        );
$tidy = tidy_parse_string($str, $opts,'latin1');
tidy_clean_repair($tidy);
$str = tidy_get_output($tidy);      
//print $str."\n";

最佳答案

您需要多字节支持。特别是,mb_encode_numericentity() :

$convmap= array(0x0100, 0xFFFF, 0, 0xFFFF);
$encutf= mb_encode_numericentity($utf, $convmap, 'UTF-8');
$iso= utf8_decode($encutf);

(这不会触及 <&" 等,因此您可能还需要预先使用 htmlspecialchars()。)

关于php - 在 PHP 中将 utf8 转换为 latin1。所有大于 255 的字符都转换为 char 引用,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/3231819/

相关文章:

windows - Emacs 在进程缓冲区中显示 ^M

javascript - 在javascript中检测浏览器字符支持?

.net - 如何使用 GetBytes(string) 检查是否存在将转换为 "?"的字符

macos - Git check out /删除带有特殊字符的文件

python - 如何将字符集损坏的字符串恢复为 unicode?

php - 在配置 PHP 以使用 mySQL 时遇到问题

php - 在调用使用命名空间的类时,您能避免指定命名空间吗?

Php Activerecord,更新对象的 NOW()

php - 替换 $_GET 以使其从命令行工作

php - php array_column 函数的逆函数?