substr是不安全的

今天遇到一个问题,数据库中保存的内容通过php在页面无法显示,如果将内容换行或加个空格或者随便加点其他内容就能正常显示。

非常的诡异,显示的内容是通过截取得到的。代码非常简单

substr($pMarketInfo['description'], 0, 150) . '...';

原始内容是:

Set on a huge 809m2 block, there is plenty of room for the pets and the little ones and with side access
• Floor to ceiling tiles in the bathroom
• Built in robe to main bedroom

最后终于查明了原因。用substr截取内容,到第150个正好碰到了'•'这个特殊符号,substr是不安全的,他截取的是字节(bytes),a占一个字节,b占一个字节。汉字及有些符号会占用多字节(到底占几个跟编码有关),所以他会将'•'这个特殊符号一截两半,变成不完整的。

php解析的时候由于不认得这半个字符,造成中断,所以最终不显示。
安全的做法是使用

mb_substr($pMarketInfo['description'], 0, 150, 'utf-8') . '...';

比substr()多出一个编码参数,如果不指定会使用内部的编码。内部编码通过mb_internal_encoding()获得。

//输出:我们都
echo mb_substr('我们都是好孩子hehe',0,9);

echo "<br>";
//输出:我们都是好孩子he
echo mb_substr('我们都是好孩子hehe',0,9,'utf-8');

第一个是以三个字节为一个中文,这就是utf-8编码的特点,下面加上utf-8字符集说明,所以,是以一个字为单位来截取的。

注:

ANSI    中文字符2、英文字符1字节
UTF-8   中文字符3、英文字符1字节
Unicode  中文字符2、英文字符2字节

原文地址:https://www.cnblogs.com/mafeifan/p/3275194.html