我不能更改PHP上的字符串编码


I can't change string encoding on PHP

<?php
   $str = "Text";
   $str = mb_convert_encoding($str, "UTF-8", mb_detect_encoding($str));
   echo mb_detect_encoding($str);
?>

这段代码给我"ASCII"作为输出。为什么?

您的字符串没有UTF-8特定字符,只有ASCII。

添加一个:

$str = "Text È";
$str = mb_convert_encoding($str, "UTF-8", mb_detect_encoding($str));
echo mb_detect_encoding($str);

您现在将得到UTF-8作为输出,如本演示所示。

但是,您不需要运行转换以获得UTF-8作为输出,mb_detect_encoding()在没有此步骤的情况下拾取字符串为UTF-8

我的假设是,由于ASCII是UTF-8的子集,因此纯ASCII"转换"为UTF-8将与ASCII无法区分。