加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 站长学院 > PHP教程 > 正文

在PHP中将utf8转换为latin1. 255以上的所有字符都转换为char引用

发布时间:2020-12-13 13:33:42 所属栏目:PHP教程 来源:网络整理
导读:我需要将UTF-8中的文本转换为ISO-8859-1中编码的文本,这样任何不属于ISO-8859-1集的字符都将变成字符引用. (ex#946;) 示例:我想将文字转换为 hello é β 水 成 hello é #946; #27700; 我在PHP中做这一切.我尝试了内置函数,iconv,整洁和组合,仍然无法获得
我需要将UTF-8中的文本转换为ISO-8859-1中编码的文本,这样任何不属于ISO-8859-1集的字符都将变成字符引用. (exβ)

示例:我想将文字转换为

hello é β 水

hello é β 水

我在PHP中做这一切.我尝试了内置函数,iconv,整洁和组合,仍然无法获得可靠的解决方案.

这是我到目前为止所拥有的

// 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,0xFFFF);
$encutf= mb_encode_numericentity($utf,$convmap,'UTF-8');
$iso= utf8_decode($encutf);

(这不会触及<,&,“等,所以你可能也需要预先使用htmlspecialchars().)

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读