MacBook avec code sur un bureau

PHP – mb_strlen to regain the size of a character chain and not strlen

By default I’ve seen a lot of code using strlen to retrieve a character string size. Unfortunately this method returns the number of bytes used rather than the number of characters. That is, depending on your encoding, you’re going to have differences of +/- 1 character.

To avoid this, you could do:

strlen (utf8_encode($string)) 

But this uses two methods whereas the mb_strlen method automatically takes encoding into account

mb_strlen ($string) 

Leave a comment