PHP 字符串将编码从 utf8 转换为 cp1251,并通过 html-mnemonic 替换不可能的字符

PHP string convert encoding from utf8 to cp1251 with replace impossible characters via html-mnemonics

提问人:userlond 提问时间:6/8/2017 最后编辑:userlond 更新时间:6/8/2017 访问量:2779

问:

我将字符串编码从宽编码转换为有限编码。我需要保留一些未包含在 cp1251 中的字符。utf8cp1251

在 python 2.x 中有一个特殊函数,它在编码转换过程中将不可能的字符替换为 html 实体:

# -*- coding: utf-8 -*-

s_in = "Ø 125 mm".decode('utf8')
s_out = s_in.encode('cp1251', 'xmlcharrefreplace')
print s_out # prints Ø 125 mm

ideone上的现场例子

PHP 中是否有任何现成的 func/lib 来完成任务?

我的代码是:

<?php
$in = 'Ø 125 mm';
$out = mb_convert_encoding($in, 'cp1251', 'utf8');
echo $out; // prints ? 125 mm

sandbox.onlinephpfunctions 上的实时示例

PHP 字符串 编码 UTF-8 MB-CONVERT-ENCODING

评论

0赞 Kazz 6/8/2017
php.net/manual/en/function.htmlentities.php
0赞 ASR 6/8/2017
尝试json_encode - 请看这里 sandbox.onlinephpfunctions.com/code/...
0赞 userlond 6/8/2017
@ASR,json_encode输出 \u00d8 125 mm
0赞 userlond 6/8/2017
@Kazz,据我所知,htmlentities 将它所能的所有内容替换为 html 实体,而不仅仅是字符,不以目标编码呈现。在我的示例中,它产生了正常的结果,但它将有效的 cp1251 符号转换为 html 实体 sandbox.onlinephpfunctions.com/code/......以为,它满足了我目前的需求,它看起来不像是完全有效的解决方案。
2赞 Kazz 6/8/2017
那这样更好吗?strtr('<p>Ø 125 mm</p>', array_diff(get_html_translation_table(HTML_ENTITIES), get_html_translation_table(HTML_SPECIALCHARS)));

答:

0赞 Syed Aqeel 6/8/2017 #1

通过使用函数,您可以将字符串从一个编码方案转换为另一个编码方案。例:iconv()PHP

$out = iconv("UTF-8", "CP1251//IGNORE", $in);

如果附加字符串 ,则不能是 在目标字符集中表示的字符集被静默丢弃//IGNORE

有关完整说明,请参阅链接:http://php.net/manual/en/function.iconv.php

评论

0赞 userlond 6/8/2017
似乎它不转换编码,输出包含 utf8 符号
0赞 userlond 6/8/2017
很奇怪,但它返回了一些虚假的东西,所以当有一些不可能的字符时,我在数据库中有空字符串。 指令给出结果。不过,感谢您的尝试//TRANSLIT? 125 mm
0赞 ASR 6/8/2017 #2

尝试使用json_encodeJSON_UNESCAPED_UNICODE

$in = 'Ø 125 mm';
$out = json_encode($in, JSON_UNESCAPED_UNICODE);
echo json_decode($out, true);    

http://sandbox.onlinephpfunctions.com/code/cfd9f38ed7ad8b668285be31004bfe2578da6436

评论

0赞 userlond 6/8/2017
输出包含 CP1251 中未表示的 UTF8 字符