duanhui4160 2017-11-10 11:26
浏览 119
已采纳

iconv() - 如何检测违规字符?

I use iconv() to convert CSV data from UTF-8 to Windows-1252.

$converted = iconv("UTF-8", "Windows-1252", $csvData);

In some cases, iconv() failed quietly, returning false.

I also tried using //TRANSLIT but `iconv()´ returns false here as well.

When i add the //IGNORE statement to the target charset, the conversion succeeds, but that means one or more character(s) got lost.

I can stick to //IGNORE but i would like to find out which character(s) are causing the problem.

How can i do this?

  • 写回答

1条回答 默认 最新

  • douxiong3245 2017-11-13 08:09
    关注

    It was bad idea to work with string as char array (see question comments) because php string type

    Internally, PHP strings are byte arrays. As a result, accessing or modifying a string using array brackets is not multi-byte safe, and should only be done with strings that are in a single-byte encoding such as ISO-8859-1.

    So we can use mb_substr for utf-8 and work with symbols not bytes

    error_reporting('E_ALL & !E_NOTICE');
    $yourString = "test bad ☺ string";
    $convertString = '';
    $badChars = [];
    
    if (iconv("UTF-8", "Windows-1252", $yourString) === false) {       
        for($i = 0, $stringLength = mb_strlen($yourString); $i < $stringLength; $i++) {
            $char = mb_substr($yourString, $i, 1);
            $convertChar = iconv("UTF-8", "Windows-1252", $char);
    
            if ($convertChar === false) {
                $badChars[$i] = $char;
            } else {
                $convertString .= $convertChar;
            }   
        }
    } else {
        $convertString = iconv("UTF-8", "Windows-1252", $yourString);
    }
    
    var_dump($badChars, $convertString);
    

    Result array(1) { [9]=> string(3) "☺" } string(16) "test bad string"

    P.S. The next time I will give a more detailed answer with the code. My mistake

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥15 我想咨询一下路面纹理三维点云数据处理的一些问题,上传的坐标文件里是怎么对无序点进行编号的,以及xy坐标在处理的时候是进行整体模型分片处理的吗
  • ¥15 CSAPPattacklab
  • ¥15 一直显示正在等待HID—ISP
  • ¥15 Python turtle 画图
  • ¥15 关于大棚监测的pcb板设计
  • ¥15 stm32开发clion时遇到的编译问题
  • ¥15 lna设计 源简并电感型共源放大器
  • ¥15 如何用Labview在myRIO上做LCD显示?(语言-开发语言)
  • ¥15 Vue3地图和异步函数使用
  • ¥15 C++ yoloV5改写遇到的问题