【问题标题】:PHP conversion from utf8_general_ci to latin1_swedish_ci从 utf8_general_ci 到 latin1_swedish_ci 的 PHP 转换
【发布时间】:2015-06-29 01:33:28
【问题描述】:

我从网站接收大量数据,所有这些字符串值都需要添加到我们的数据库中。

在插入数据库期间,SQL 有时会抛出以下错误:

Warning:  PDOStatement::execute(): SQLSTATE[HY000]: General error: 1267 Illegal mix of collations (latin1_swedish_ci,IMPLICIT) and (utf8_general_ci,COERCIBLE)

数据库表实际上设置为使用 Latin1。

使用 json_encode() 对我的值进行编码后,我发现了此错误发生的原因。字符串之间的UTF序列,代表一些特殊字符,需要转换成它们的实际值:

编码字符串: 候选人\u00e2\u0080\u0099的个人情况

在本例中,序列 \u00e2\u0080\u0099 代表一个 '。

只要有几个不同的序列,我也知道我想要/需要替换它们的值,但我正在努力转换。

我尝试了几种方法,但都没有成功,

使用 str_replace:

str_replace('\\u00e2\\u0080\\u0099', '\'', ($string));

没有改变字符串中的任何内容

使用 mb_functions:

$encodedStr = mb_convert_encoding($string, 'ASCII')

给我留下了一些神秘的东西??而不是 UTF 序列,但它不会引发数据库错误,但它仍然不是我需要的。

使用 preg_replace:

preg_replace('/\\u00e2\\u0080\\u0099/', '\'', $string)


抛出错误:PCRE 在偏移量 1 处不支持 \L、\l、\N{name}、\U 或 \u

我已经尝试了更多选项,但是当我开始强制解决这个问题时,我想到了三个选项,我只是想不通为什么这些功能,尤其是 str_replace 不能以预期的方式工作。

【问题讨论】:

    标签: php string preg-replace str-replace mb-convert-encoding


    【解决方案1】:

    我终于解决了这个问题。以防有人在同样的问题上挣扎。 对我有用的解决方案已发布在

    I have a string with "\u00a0", and I need to replace it with "" str_replace fails

    private function convert($string) {
        /* Strings to remove:    
         *      \u00a0 = 
         *      \u00e2\u0080\u0099 = '
         *      
         */
        $string = str_replace(chr(194).chr(160), '', $string);  //removes \u00a0
        $string = str_replace('â', '', $string);  //removes \u00e2
        $string = str_replace(chr(194).chr(128).chr(194).chr(153), '\'', $string);  //removes \u0080\u0099
    
        return $string;
        }
    

    【讨论】:

      猜你喜欢
      • 2012-09-27
      • 2011-06-13
      • 2015-07-28
      • 2011-10-02
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2012-04-12
      • 1970-01-01
      相关资源
      最近更新 更多