首頁 >後端開發 >PHP問題 >PHP如何把字串改成UTF8?

PHP如何把字串改成UTF8?

Guanhui
Guanhui原創
2020-06-15 16:32:563474瀏覽

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