首页  >  文章  >  后端开发  >  PHP如何把字符串改成UTF8?

PHP如何把字符串改成UTF8?

Guanhui
Guanhui原创
2020-06-15 16:32:563436浏览

PHP如何把字符串改成UTF8?

PHP如何把字符串改成UTF8?

在PHP中可以使用“iconv()”函数把字符串改成UTF8,该函数作用是将字符串按要求的字符编码来转换,其语法为“iconv(in,out,str)”,使用时将in设置为字符串的编码,out设置为UTF8,str设置为要转换的字符串即可。

转化示例

$str = "123456789";

$str = iconv('ASCII', 'UTF8', $str);

使用示例

<?php
//some German
$utf8_sentence = &#39;Weiß, Goldmann, Göbel, Weiss, Göthe, Goethe und Götz&#39;;

//UK
setlocale(LC_ALL, &#39;en_GB&#39;);

//transliterate
$trans_sentence = iconv(&#39;UTF-8&#39;, &#39;ASCII//TRANSLIT&#39;, $utf8_sentence);

//gives [Weiss, Goldmann, Gobel, Weiss, Gothe, Goethe und Gotz]
//which is our original string flattened into 7-bit ASCII as
//an English speaker would do it (ie. simply remove the umlauts)
echo $trans_sentence . PHP_EOL;

//Germany
setlocale(LC_ALL, &#39;de_DE&#39;);

$trans_sentence = iconv(&#39;UTF-8&#39;, &#39;ASCII//TRANSLIT&#39;, $utf8_sentence);

//gives [Weiss, Goldmann, Goebel, Weiss, Goethe, Goethe und Goetz]
//which is exactly how a German would transliterate those
//umlauted characters if forced to use 7-bit ASCII!
//(because really ä = ae, ö = oe and ü = ue)
echo $trans_sentence . PHP_EOL;

?>
<?php
$tab = array("UTF-8", "ASCII", "Windows-1252", "ISO-8859-15", "ISO-8859-1", "ISO-8859-6", "CP1256");
$chain = "";
foreach ($tab as $i)
    {
        foreach ($tab as $j)
        {
            $chain .= " $i$j ".iconv($i, $j, "$my_string");
        }
    }

echo $chain;
?>

推荐教程:《PHP教程

以上是PHP如何把字符串改成UTF8?的详细内容。更多信息请关注PHP中文网其他相关文章!

声明:
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系admin@php.cn