首页  >  文章  >  后端开发  >  php怎么把字符串转为utf-8编码

php怎么把字符串转为utf-8编码

青灯夜游
青灯夜游原创
2021-05-10 14:17:094767浏览

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