If you have problems using count_chars with a multibyte string, you can change the page encoding. Alternatively, you can also use this mb_count_chars version of the function. Basically it is mode "1" of the original function.
<?php
/**
* Counts character occurences in a multibyte string
* @param string $input UTF-8 data
* @return array associative array of characters.
*/
function mb_count_chars($input) {
$l = mb_strlen($input, 'UTF-8');
$unique = array();
for($i = 0; $i < $l; $i++) {
$char = mb_substr($input, $i, 1, 'UTF-8');
if(!array_key_exists($char, $unique))
$unique[$char] = 0;
$unique[$char]++;
}
return $unique;
}
$input = "Let's try some Greek letters: αααααΕεΙιΜμΨψ, Russian: ЙЙЫЫЩН, Czech: ěščřžýáíé";
print_r( mb_count_chars($input) );
//returns: Array ( [L] => 1 [e] => 7 [t] => 4 ['] => 1 [s] => 5 [ ] => 9 [r] => 3 [y] => 1 [o] => 1 [m] => 1 [G] => 1 [k] => 1 [l] => 1 [:] => 3 [α] => 5 [Ε] => 1 [ε] => 1 [Ι] => 1 [ι] => 1 [Μ] => 1 [μ] => 1 [Ψ] => 1 [ψ] => 1 [,] => 2 [R] => 1 [u] => 1 [i] => 1 [a] => 1 [n] => 1 [Й] => 2 [Ы] => 2 [Щ] => 1 [Н] => 1 [C] => 1 [z] => 1 [c] => 1 [h] => 1 [ě] => 1 [š] => 1 [č] => 1 [ř] => 1 [ž] => 1 [ý] => 1 [á] => 1 [í] => 1 [é] => 1 )
?>
count_chars
(PHP 4, PHP 5)
count_chars — Bir dizgedeki karakterler hakkında bilgi döndürür
Açıklama
dizge dizgesi içindeki her bayt değerini (0..255)
sayar ve sonuçları çeşitli yollarla döndürür.
Değiştirgeler
-
dizge -
İncelenecek dizge.
-
kip -
Belirtilmesi isteğe bağlı olup öntanımlı değeri 0'dır.
Dönen Değerler
kip değiştirgesine bağlı olarak
count_chars() şunlardan birini döndürür:
- 0 - Bayt değeri anahtar ve bu bayta rastlanma sıklığı değer olmak üzere bir ilişkisel dizi döner.
- 1 - Sadece rastlanma sıklığı sıfırdan büyük olan baytlarla ilgili sonuçları döndürmesi dışında 0 ile aynıdır.
- 2 - Sadece rastlanma sıklığı sıfır olan baytlarla ilgili sonuçları döndürmesi dışında 0 ile aynıdır.
- 3 - Tüm eşsiz karakterleri içeren bir dizge döner.
- 4 - Kullanılmamış karakterleri içeren bir dizge döner.
Örnekler
Örnek 1 - count_chars() örneği
<?php
$veri = "Beş N ve bir K.";
foreach (count_chars($veri, 1) as $bayt => $kaç) {
echo "Dizgede $kaç tane $bayt numaralı karakter var.\n";
}
?>
Yukarıdaki örneğin çıktısı:
Dizgede 4 tane 32 numaralı karakter var. Dizgede 1 tane 46 numaralı karakter var. Dizgede 1 tane 66 numaralı karakter var. Dizgede 1 tane 75 numaralı karakter var. Dizgede 1 tane 78 numaralı karakter var. Dizgede 1 tane 98 numaralı karakter var. Dizgede 2 tane 101 numaralı karakter var. Dizgede 1 tane 105 numaralı karakter var. Dizgede 1 tane 114 numaralı karakter var. Dizgede 1 tane 118 numaralı karakter var. Dizgede 1 tane 159 numaralı karakter var. Dizgede 1 tane 197 numaralı karakter var.
Ayrıca Bakınız
- strpos() - Bir alt dizgenin ilkinin konumunu bulur
- substr_count() - Bir dizge içinde belli bir alt dizgeden kaç tane bulunduğunu bulur
marcus33cz
01-Feb-2012 12:43
phpC2007
04-Dec-2007 08: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)...
<?php
function utf8_count_strings($stringChar)
{
$num = -1;
$lenStringChar = strlen($stringChar);
for ($lastPosition = 0;
$lastPosition !== false;
$lastPosition = strpos($textSnippet, $stringChar, $lastPosition + $lenStringChar))
{
$num++;
}
return $num;
}
?>
pzb at novell dot com
28-Jul-2007 08: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:
<?php
function is7bit($string) {
// empty strings are 7-bit clean
if (!strlen($string)) {
return true;
}
// count_chars returns the characters in ascending octet order
$str = count_chars($str, 3);
// Check for null character
if (!ord($str[0])) {
return false;
}
// Check for 8-bit character
if (ord($str[strlen($str)-1]) & 128) {
return false;
}
return true;
}
?>
Patrick Palka
10-Apr-2007 10:46
A faster unique character-checking function:
<?php
function chr_unique($string) {
return strlen(count_chars($string, 3));
}
?>
apinpratap at gmail dot com
30-Mar-2007 12:54
this code can find each characters count
<?php
$enter = 0;
$data = strtolower ($inputString);
foreach (count_chars ($data, 1) as $i => $val)
{
if ($enter == 1)
{
$enter = 0;
continue;
}
if (chr ($i) == "\n")
{
echo "There are $val instance(s) of \" Enter \" in the string.\n";
$enter = 1;
}
else
{
echo "There are $val instance(s) of \"" , chr ($i) , "\" in the string.\n";
}
}
?>
Eric Pecoraro
27-May-2005 09:31
<?php
// 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($pass,3);
function req_unique($string,$unique=3) {
if ( count(count_chars($string,1)) < $unique) {
echo 'false';
}else{
echo 'true';
}
}
?>
Alex Gemmell
14-Feb-2005 11: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
16-May-2004 05: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));
return $res;
}
/* 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
29-Jan-2002 05:27
// Usefulness of the two functions
<?php
$string="aaabbc";
// You just want to count the letter a
$acount=substr_count($string,"a");
// You want to count both letter a and letter b
$counts=count_chars($string,0);
$acount=$counts[ord("a")];
$bcount=$counts[ord("b")];
?>
maotin at hongkong dot com
31-Jan-2001 06:04
Here are some more experiments on this relatively new and extremely handy function.
<?php
$string = 'I have never seen ANYTHING like that before! My number is "4670-9394".';
foreach(count_chars($string, 1) as $chr => $hit)
echo '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).
<?php
$length_of_string = strlen($string);
$num_of_chars = strlen(count_chars($string, 3));
$diff = ($length_of_string - $num_of_chars);
if ($diff)
echo 'At least one character has been used more than once.';
else
echo 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?)
