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 素材场景中光线烘焙后灯光失效
  • ¥15 请教一下各位,为什么我这个没有实现模拟点击
  • ¥15 执行 virtuoso 命令后,界面没有,cadence 启动不起来
  • ¥50 comfyui下连接animatediff节点生成视频质量非常差的原因
  • ¥20 有关区间dp的问题求解
  • ¥15 多电路系统共用电源的串扰问题
  • ¥15 slam rangenet++配置
  • ¥15 有没有研究水声通信方面的帮我改俩matlab代码
  • ¥15 ubuntu子系统密码忘记
  • ¥15 保护模式-系统加载-段寄存器