如何检测是否必须对字符串应用utf8解码或编码?

Pen*_*m10 19 php encoding utf-8

我有从第三方网站获取的Feed,有时我必须申请utf8_decode并且有时候utf8_encode才能获得所需的可见输出.

如果错误地将相同的东西应用了两次/或者使用了错误的方法我会得到一些更难看的东西,这就是我想要改变的东西.

如何检测何时应用于字符串?

UPDATE

实际上内容返回UTF-8,但内部有部分不返回.

bis*_*sko 55

我不能说我可以依靠mb_detect_encoding().过了一段时间有一些怪异的误报.

我发现在每种情况下运作良好的最普遍的方式是:

if (preg_match('!!u', $string))
{
   // This is UTF-8
}
else
{
   // Definitely not UTF-8
}
Run Code Online (Sandbox Code Playgroud)

  • "这只是一个空的正则表达式.!是分隔符,你是修正器." 解决方案确实很聪明,但需要更详细的解释,所以我问了一下 - http://stackoverflow.com/questions/10855682/explain-this-utf-8-detection-regex (5认同)
  • 谢谢!这是一个非常聪明的技巧;-)因为我绝对没有关于它如何工作的线索,我钻研了PHP文档来找到[this](http://us2.php.net/manual/en/reference.pcre. pattern.modifiers.php):`u(PCRE8)这个修饰符打开了与Perl不兼容的PCRE的附加功能.模式字符串被视为UTF-8.此修饰符可从Unix上的PHP 4.1.0或更高版本以及win32上的PHP 4.2.3获得.自PHP 4.3.5起,检查模式的UTF-8有效性.`无论如何,谢谢你! (4认同)
  • +1实现了一个utf8_validate(),使用您的解决方案将字符串转换为utf8,如果不是,则作为魅力! (3认同)
  • 甚至不需要regexp中的点`preg_match('!! u',$ str)`工作正常 (2认同)

Geo*_*DRA 6

function str_to_utf8 ($str) {
    $decoded = utf8_decode($str);
    if (mb_detect_encoding($decoded , 'UTF-8', true) === false)
        return $str;
    return $decoded;
}

var_dump(str_to_utf8("« Chrétiens d'Orient » : la RATP fait marche arrière"));
//string '« Chrétiens d'Orient » : la RATP fait marche arrière' (length=56)
var_dump(str_to_utf8("« Chrétiens d'Orient » : la RATP fait marche arrière"));
//string '« Chrétiens d'Orient » : la RATP fait marche arrière' (length=56)
Run Code Online (Sandbox Code Playgroud)