How to count the characters in a string
Short answer
mb_strlen() counts characters in any language:
<?php
echo mb_strlen('Привет');Output:
6Bytes, not characters
strlen() returns the number of bytes. A Cyrillic letter takes two in UTF-8:
<?php
echo strlen('Привет'), ' ', strlen('Hello');Output:
12 5How many times a character occurs
substr_count() does that:
<?php
echo substr_count('banana', 'a');Output:
3Functions 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.