Если вы имеете дело с UTF-8 (что вам действительно следует учитывать, imho), ни одно из опубликованных решений (с использованием strlen, str_split или count_chars) не будет работать, так как все они обрабатывают один байт как один символ (который является очевидно, что это не так для UTF-8).
<?php
$treat_spaces_as_chars = true;
// contains hälöwrd and a space, being 8 distinct characters (7 without the space)
$string = "hällö wörld";
// remove spaces if we don't want to count them
if (!$treat_spaces_as_chars) {
$string = preg_replace('/\s+/u', '', $string);
}
// split into characters (not bytes, like explode() or str_split() would)
$characters = preg_split('//u', $string, -1, PREG_SPLIT_NO_EMPTY);
// throw out the duplicates
$unique_characters = array_unique($characters);
// count what's left
$numer_of_characters = count($unique_characters);
Если вы хотите выбросить все несловарные символы:
<?php
$ignore_non_word_characters = true;
// contains hälöwrd and PIE, as this is treated as a word character (Greek)
$string = "h,ä*+l•π‘°’lö wörld";
// remove spaces if we don't want to count them
if ($ignore_non_word_characters) {
$string = preg_replace('/\W+/u', '', $string);
}
// split into characters (not bytes, like explode() or str_split() would)
$characters = preg_split('//u', $string, -1, PREG_SPLIT_NO_EMPTY);
// throw out the duplicates
$unique_characters = array_unique($characters);
// count what's left
$numer_of_characters = count($unique_characters);
var_dump($characters, $unique_characters, $numer_of_characters);