温馨提示×

温馨提示×

您好,登录后才能下订单哦!

密码登录×
登录注册×
其他方式登录
点击 登录注册 即表示同意《亿速云用户服务条款》

php如何把字符串转为utf-8编码

发布时间:2021-05-10 14:34:16 来源:亿速云 阅读:1486 作者:小新 栏目:编程语言

这篇文章给大家分享的是有关php如何把字符串转为utf-8编码的内容。小编觉得挺实用的,因此分享给大家做个参考,一起跟随小编过来看看吧。

php有什么特点

1、执行速度快。2、具有很好的开放性和可扩展性。3、PHP支持多种主流与非主流的数据库。4、面向对象编程:PHP提供了类和对象。5、版本更新速度快。6、具有丰富的功能。7、可伸缩性。8、功能全面,包括图形处理、编码与解码、压缩文件处理、xml解析等。

php把字符串转为utf-8编码的方法:首先使用mb_detect_encoding()获取字符串原来的编码;然后通过“mb_convert_encoding(字符串, '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如何把字符串转为utf-8编码”这篇文章就分享到这里了,希望以上内容可以对大家有一定的帮助,让大家可以学到更多知识,如果觉得文章不错,可以把它分享出去让更多的人看到吧!

向AI问一下细节

免责声明:本站发布的内容(图片、视频和文字)以原创、转载和分享为主,文章观点不代表本网站立场,如果涉及侵权请联系站长邮箱:is@yisu.com进行举报,并提供相关证据,一经查实,将立刻删除涉嫌侵权内容。

AI