substr doesn't work fine with utf8

跟風遠走 提交于 2019-12-10 13:54:26

问题


I am using a substr method to access the first 20 characters of a string. It works fine in normal situation, but while working on rtl languages (utf8) it gives me wrong results (about 10 characters are shown). I have searched the web but found nth useful to solve this issue. This is my line of code:

substr($article['CBody'],0,20);

Thanks in advance.


回答1:


If you’re working with strings encoded as UTF-8 you may lose characters when you try to get a part of them using the PHP substr function. This happens because in UTF-8 characters are not restricted to one byte, they have variable length to match Unicode characters, between 1 and 4 bytes.

You can use mb_substr(), It works almost the same way as substr but the difference is that you can add a new parameter to specify the encoding type, whether is UTF-8 or a different encoding.

Try this:

$str = mb_substr($article['CBody'], 0, 20, 'UTF-8');

echo utf8_decode($str); 

Hope this helps.




回答2:


Use this instead, here is extra text to make the body long enough. This will handle multi-byte characters. http://php.net/manual/en/function.mb-substr.php



来源:https://stackoverflow.com/questions/14785682/substr-doesnt-work-fine-with-utf8

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!