Encodera

Thanks for reading!

Donate to the site — we work hard for you.

How to count the characters in a string

Short answer

mb_strlen() counts characters in any language:

<?php
 
echo mb_strlen('Привет');

Output:

6

Bytes, not characters

strlen() returns the number of bytes. A Cyrillic letter takes two in UTF-8:

<?php
 
echo strlen('Привет'), ' ', strlen('Hello');

Output:

12 5

How many times a character occurs

substr_count() does that:

<?php
 
echo substr_count('banana', 'a');

Output:

3

Functions used in this recipe

  • mb_strlen — Returns the number of characters in a string.
  • strlen — Returns the length of a string in bytes.
  • substr_count — Counts how many times a substring occurs in a string.

Thanks for reading!

Donate to the site — we work hard for you.