PHP:查找字符串中不同字母的数量

时间:2013-03-13 16:44:49

标签: php

我想找一个字符串包含多少个唯一字符。例子:

"66615888"    contains 4 digits (6 1 5 8).
"12333333345" contains 5 digits (1 2 3 4 5).

5 个答案:

答案 0 :(得分:16)

echo count( array_unique( str_split( '66615888')));

Demo

文档:

  1. count() - 计算数组中元素的数量
  2. array_unique() - 查找数组中的唯一元素
  3. str_split() - 将字符串拆分为数组

答案 1 :(得分:10)

count_chars为您提供了char => frequency的地图,您可以使用array_sum来总结:

$count = array_sum(count_chars($str));

或者,您可以使用3 count_chars模式,它会为您提供包含所有唯一字符的字符串:

$count = strlen(count_chars($str, 3));

答案 2 :(得分:2)

PHP有一个计算字符数的函数。

$data = "foobar";
$uniqued = count_chars($data, 3);// return string(5) "abfor"
$count = strlen($uniqued);

请参阅文档here

答案 3 :(得分:1)

您可以使用以下脚本:

<?php
  $str1='66615888';
  $str2='12333333345';
  echo 'The number of unique characters in "'.$str1.'" is: '.strlen(count_chars($str1,3)).' ('.count_chars($str1,3).')'.'<br><br>';
  echo 'The number of unique characters in "'.$str2.'" is: '.strlen(count_chars($str2,3)).' ('.count_chars($str2,3).')'.'<br><br>';
?>

输出:

&#34; 66615888&#34;中的唯一字符数是:4(1568)

&#34; 12333333345&#34;中的唯一字符数是:5(12345)

此处模式count_chars()中的PHP字符串函数3生成一个包含所有唯一字符的数组。

PHP字符串函数strlen()生成存在的唯一字符总数。

答案 4 :(得分:0)

这里是另一个也可以处理多字节字符串的版本:

echo count(array_keys(array_flip(preg_split('//u', $str, null, PREG_SPLIT_NO_EMPTY))));