首頁  >  文章  >  後端開發  >  php怎麼把字串轉為utf-8編碼

php怎麼把字串轉為utf-8編碼

青灯夜游
青灯夜游原創
2021-05-10 14:17:094901瀏覽

php把字串轉為utf-8編碼的方法:首先使用mb_detect_encoding()取得字串原來的編碼;然後透過「mb_convert_encoding(字串, 'UTF-8', 字串的原本編碼)」語句進行轉換即可。

php怎麼把字串轉為utf-8編碼

本教學操作環境:windows7系統、PHP7.1版,DELL G3電腦

php將任意編碼的字串內容轉換成utf-8

function str_to_utf8 ($str = '') {
$current_encode = mb_detect_encoding($str, array("ASCII","GB2312","GBK",'BIG5','UTF-8'));  //获取原来编码
$encoded_str = mb_convert_encoding($str, 'UTF-8', $current_encode); //将原来编码转换成utf-8 大小写都可以
return $encoded_str;
}

相關函數說明:

1、mb_detect_encoding()

mb_detect_encoding — 偵測字元的編碼

語法:

mb_detect_encoding ( string $str , mixed $encoding_list = mb_detect_order() , bool $strict = false )

參數:

  • #str

    待檢查的字串。

  • encoding_list

    encoding_list 是一個字元編碼清單。編碼順序可以由數組或逗號分隔的列表字串指定。

    如果省略了 encoding_list 將會使用 detect_order。

  • strict

    strict 指定了是否嚴格地偵測編碼。預設是 false。

傳回值:

  • 偵測到的字元編碼,或無法偵測指定字串的編碼時傳回 false。

2、mb_convert_encoding()

mb_convert_encoding — 轉換字元的編碼

語法:

mb_convert_encoding ( array|string $string , string $to_encoding , array|string|null $from_encoding = null )

將string 類型str 的字元編碼從可選的from_encoding 轉換到to_encoding。當參數 string 是一個 array 時,將遞歸轉換它所有的 string 值。

參數

  • string

    要編碼的 string 或 array。

  • to_encoding

    string 要轉換成的編碼類型。

  • from_encoding

    在轉換前透過字元代碼名稱來指定。它可以是一個 array 也可以是逗號分隔的枚舉列表。如果沒有提供 from_encoding,則會使用內部(internal)編碼。

傳回值:

  • 編碼後的 string。成功時傳回編碼後的 string 或 array, 或在失敗時傳回 false。

推薦學習:《PHP影片教學

以上是php怎麼把字串轉為utf-8編碼的詳細內容。更多資訊請關注PHP中文網其他相關文章!

陳述:
本文內容由網友自願投稿,版權歸原作者所有。本站不承擔相應的法律責任。如發現涉嫌抄襲或侵權的內容,請聯絡admin@php.cn