php截取字符串乱码问题

substr()函数用来截取字符串,是按字节截取,mb_substr()是按照字符截取,并且可以指定编码(以utf-8为例)。

比如:

$str = “测试A4abcd截取字符串乱码问题!”;
$sub = substr($str, 0,5);
var_dump ($sub);
echo bin2hex($sub);


因为utf-8编码中一个汉字占三个字节,例子中截取了第一个汉字和第二个汉字的前两个字节,共5个字节。第二个字节乱码。而采用mb_substr()则不会出现乱码:

类似的还有很会出现乱码的函数。php提供了一批多字节处理函数(mb_开头),用来处理汉字等多字节编码。

比如使用mb_split()代替explode()。

 

 

说明

string substr ( string $string , int $start [, int $length ] )

返回字符串 stringstartlength 参数指定的子字符串。

2011年12月18日 | 归档于 PHP/Python/C
标签:
本文目前尚无任何评论.

发表评论

XHTML: 您可以使用这些标签: <a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code lang=""> <del datetime=""> <em> <i> <q cite=""> <strike> <strong>