php截取中文字符串不乱码的方法_php实例

WBOY
Release: 2016-05-17 08:51:59
Original
1240 people have browsed it

GBK编码截取示例

复制代码 代码如下:

$str = '我是谁';  //gbk编码的字符串
echo mb_substr($str, 0, 1, 'gbk'); //输出 我

mb_substr方法比substr多一个参数,用来指定字符串编码。

utf-8编码截取示例

[code]
$str = '我abc是谁';  //utf-8编码的字符串
echo mb_substr($str, 0, 2, 'utf-8'); //输出 我a
[/code

中英混合也完全没有问题。

友情提示

使用的时候要注意php文件的编码,和网页显示时的编码。

使用这个mb_substr方法要事先知道字符串的编码,如果不知道编码,就需要判断,mbstring库还提供了mb_check_encoding来检验字符串编码,但还不完善。

Related labels:
source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template
About us Disclaimer Sitemap
php.cn:Public welfare online PHP training,Help PHP learners grow quickly!