Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

substr doesn't work fine with utf8

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.

like image 937
Az Dr Avatar asked Feb 09 '13 06:02

Az Dr


1 Answers

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.

like image 119
AlphaMale Avatar answered Oct 21 '22 12:10

AlphaMale