Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to get the exact number of multibyte characters?

Tags:

php

multibyte

I tried:

mb_strlen('普通话');
strlen('普通话');

both of them output 9,while in fact there are only 3 characters.

What's the right way to count characters?

like image 775
omg Avatar asked Mar 01 '23 07:03

omg


2 Answers

you should make sure to specify the encoding in the second parameter

ie

mb_strlen('普通话', 'UTF-8');

see the manual

like image 56
RageZ Avatar answered Mar 02 '23 19:03

RageZ


If you don't have access to the mb string extension this also works (and I believe it's faster):

strlen(utf8_decode('普通话')); // 3
like image 31
Alix Axel Avatar answered Mar 02 '23 20:03

Alix Axel