LMLPHP后院

PHP编码转换减号(连接符)无法转换问题技术

maybe yes 发表于 2015-01-23 16:03

使用 PHP 的 iconv 或 mb_convert_encoding 函数进行编码转换,比如将 gb2312 转换为 utf-8 编码,在出现某些特殊字符(减号,连接符)时,不能正常工作,可能会变成问号"?"或者"C"。尝试了多种方法,依然不能很好的解决这个问题。如下代码,在声明了 //IGNORE 后遇到连接符号"-"仍然会变成符号"?"。

<?php
$html = iconv($charset, 'utf-8//IGNORE', $html);

按照 PHP 官网手册中网友提供的解决方法进行尝试,仍然不能解决问题,不知道是不是我本地 PHP 版本的问题。

解决方法一:
Please note that iconv('UTF-8', 'ASCII//TRANSLIT', ...) doesn't work properly when locale category LC_CTYPE is set to C or POSIX. You must choose another locale otherwise all non-ASCII characters will be replaced with question marks. This is at least true with glibc 2.5.
Example:
[翻译]
请注意 iconv 在语言环境类别 LC_CTYPE 类别设置为 C 或者 POSIX 时不能正常的工作。你必须选择另一个语言,否则所有的非 ASCLL 编码将被替换成问号"?"。这个问题在 glibc 2.5 以下是真实的。
举例如下:

<?php
setlocale(LC_CTYPE, 'POSIX');
echo iconv('UTF-8', 'ASCII//TRANSLIT', "Žluťoučký kůň\n");
// ?lu?ou?k? k??

setlocale(LC_CTYPE, 'cs_CZ');
echo iconv('UTF-8', 'ASCII//TRANSLIT', "Žluťoučký kůň\n");
// Zlutoucky kun

解决方法二:
That will strip invalid characters from UTF-8 strings (so that you can insert it into a database, etc.). Instead of "none" you can also use the value 32 if you want it to insert spaces in place of the invalid characters.

<?php
ini_set('mbstring.substitute_character', "none");
$text= mb_convert_encoding($text, 'UTF-8', 'UTF-8');
相关文章
2024-03-29 10:09:01 1711678141 0.008894