PHP Doku:: Gibt Informationen über die in einem String enthaltenen Zeichen zurück - function.count-chars.html

Verlauf / Chronik / History: (1) anzeigen

Sie sind hier:

Ein Service von Reinhard Neidl - Webprogrammierung.





(PHP 4, PHP 5)

count_charsGibt Informationen über die in einem String enthaltenen Zeichen zurück


mixed count_chars ( string $string [, int $mode = 0 ] )

Zählt die Häufigkeit des Vorkommens jedes einzelnen Byte-Wertes (0..255) in string und gibt sie auf verschiedene Arten zurück.



Die zu untersuchende Zeichenkette.


Siehe Rückgabewerte.


Abhängig von mode gibt count_chars() eine der folgenden Möglichkeiten zurück:

  • 0 - ein Array mit den Byte-Werten als Schlüssel und deren jeweiliger Häufigkeit als Wert.
  • 1 - wie 0, allerdings werden nur Byte-Werte ausgegeben, die mindestens einmal vorkommen.
  • 2 - wie 0, allerdings werden nur Byte-Werte, die nicht vorkommen, aufgelistet.
  • 3 - eine Zeichenkette, die alle vorkommenden Zeichen enthält.
  • 4 - eine Zeichenkette, die alle nicht vorkommenden Zeichen enthält.


Beispiel #1 count_chars()-Beispiel

"Zwei Z und ein F.";

foreach (
count_chars($data1) as $i => $val) {
"Es gibt $val Vorkommen von \"" chr($i) , "\" in der Zeichenkette.\n";

Das oben gezeigte Beispiel erzeugt folgende Ausgabe:

Es gibt 4 Vorkommen von " " in der Zeichenkette.
Es gibt 1 Vorkommen von "." in der Zeichenkette.
Es gibt 1 Vorkommen von "F" in der Zeichenkette.
Es gibt 2 Vorkommen von "Z" in der Zeichenkette.
Es gibt 1 Vorkommen von "d" in der Zeichenkette.
Es gibt 2 Vorkommen von "e" in der Zeichenkette.
Es gibt 2 Vorkommen von "i" in der Zeichenkette.
Es gibt 2 Vorkommen von "n" in der Zeichenkette.
Es gibt 1 Vorkommen von "u" in der Zeichenkette.
Es gibt 1 Vorkommen von "w" in der Zeichenkette.

Siehe auch

  • strpos() - Sucht das erste Vorkommen des Suchstrings
  • substr_count() - Ermittelt, wie oft eine Zeichenkette in einem String vorkommt

9 BenutzerBeiträge:
- Beiträge aktualisieren...
4.12.2007 16:42
Here's a function to count number of strings in a string. It can be used as a simple utf8-enabled count_chars (but limited to a single mode)...

function utf8_count_strings($stringChar)
$num = -1;
$lenStringChar = strlen($stringChar);
    for (
$lastPosition = 0;
$lastPosition !== false;
$lastPosition = strpos($textSnippet, $stringChar, $lastPosition + $lenStringChar))
pzb at novell dot com
29.07.2007 3:29
This function is great for input validation.  I frequently need to check that all characters in a string are 7-bit ASCII (and not null).  This is the fastest function I have found yet:

function is7bit($string) {
// empty strings are 7-bit clean
if (!strlen($string)) {
// count_chars returns the characters in ascending octet order
$str = count_chars($str, 3);
// Check for null character
if (!ord($str[0])) {
// Check for 8-bit character
if (ord($str[strlen($str)-1]) & 128) {
Patrick Palka
11.04.2007 5:46
A faster unique character-checking function:

function chr_unique($string) {
strlen(count_chars($string, 3));
apinpratap at gmail dot com
30.03.2007 8:54
this code can find each characters count

= 0;
$data = strtolower ($inputString);
foreach (
count_chars ($data, 1) as $i => $val)
        if (
$enter == 1)
$enter = 0;
        if (
chr ($i) == "\n")
"There are $val instance(s) of \" Enter \" in the string.\n";
$enter = 1;
"There are $val instance(s) of \"" , chr ($i) , "\" in the string.\n";
Eric Pecoraro
27.05.2005 16:31

// Require (n) unique characters in a string
// Modification of a function below which ads some flexibility in how many unique characters are required in a given string.

$pass = '123456' ; // true
$pass = '111222' ; // false


req_unique($string,$unique=3) {
    if (
count(count_chars($string,1)) < $unique) {

Alex Gemmell
14.02.2005 19:03
Use: Great for checking for unique characters in a password.

I wanted to check that my website users, when registering a user account, chose a "valid" (not-so-easily-guessed) password.

One of the many checks was that the password must have 6 unique characters.  I was tying myself in knots with all kinds of recursive array calling when I was offered this wonderful one line solution:

function check_password($password) {

   #Have 6 unique characters
   if (count(count_chars($password, 1)) < 6) return false;

   # other checks returning false as necessary

   return true;

I cannot claim this wonderful line for myself - a Mr Lynch suggested this to me.  Thanks!
seb at synchrocide dot net
17.05.2004 0:08
After much trial and error trying to create a function that finds the number of unique characters in a string I same across count_chars() - my 20+ lines of useless code were wiped for this:

function unichar($string) {
$two= strtolower(str_replace(' ', '', $string));
$res = count(count_chars($two, 1));

/* examples :: */

echo unichar("bob"); // 2
echo unichar("Invisibility"); //8
echo unichar("The quick brown fox slyly jumped over the lazy dog"); //26


I have no idea where this could be used, but it's quite fun
mlong at mlong dot org
30.01.2002 1:27
// Usefulness of the two functions


// You just want to count the letter a

// You want to count both letter a and letter b
maotin at hongkong dot com
1.02.2001 2:04
Here are some more experiments on this relatively new and extremely handy function.

= 'I have never seen ANYTHING like that before! My number is "4670-9394".';

count_chars($string, 1) as $chr => $hit)
'The character '.chr(34).chr($chr).chr(34).' has appeared in this string '.$hit.' times.<BR>';

#The result looks like
#The character " " has appeared in this string 11 times.

echo count_chars($string,3);
#The output is '!"-.034679AGHIMNTYabefhiklmnorstuvy'

echo strlen($string).' is not the same as '.strlen(count_chars($string, 3));

#This shows that '70 is not the same as 36'

As we can see above:

1)If you cares only about what is in the string, use count_chars($string, 1) and it will return an (associative?) array of what shows up only.

2) Either I misunderstood what the manul actually said, or it does not work the way it described: count_chars($strting, 3) actually returned a string of what characters are in the string, not a string of their byte-values (which is great because a string of numbers would be much harder to handle);

3)This is a short version of password checking: get the original string's length, then compare with the length of the string returned by count_chars($string,3). 

= strlen($string);
$num_of_chars = strlen(count_chars($string, 3));

$diff = ($length_of_string - $num_of_chars);

if (
'At least one character has been used more than once.';
'All character have been used only once.;

Note that since $num_of_chars gives no information about the actual number of occurance, we cannot go any further by the same rationale and say when $diff =2 then 2 characters showed up twice; it might be 1 character showd up 3 times, we have no way to tell (a good tolerance level setter, though).  You have to get the array and check the values if you want to have more control.

4) Final trick: now we have a primitive way to count the number of words in a string! (or do we have a fuction for that already?)

PHP Powered Diese Seite bei
The PHP manual text and comments are covered by the Creative Commons Attribution 3.0 License © the PHP Documentation Group - Impressum - mail("TO:Reinhard Neidl",...)