算上所有的字母出现在一个字符串PHP [英] count the occurrences of all the letters in a string PHP

查看:111
本文介绍了算上所有的字母出现在一个字符串PHP的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我要计算一个字符串的所有字母出现的频率。说我有

  $海峡=cdcdcdcdeeeef;

我可以使用str_split和array_count_values​​实现这一目标。

  array_count_values​​(str_split($ STR));

想知道是否有另一种方式来做到这一点,而不串转换到一个数组?谢谢


解决方案

您不必将其转换成阵列()您可以使用 substr_count()来实现相同的。


  

substr_count - 计数子出现的次数


 < PHP
$海峡=cdcdcdcdeeeef;
回声substr_count($海峡,'C');
?>

PHP手册

substr_count()返回草垛发生串针子的次数。请注意,针是大小写敏感的。

编辑:

很抱歉的误解,可以使用 count_chars 有字符串中的每个字符的计数值。举个例子:

 < PHP
$海峡=cdcdcdcdeeeef;的foreach(count_chars($ STR,1)$ STRR => $值){
   回声CHR($ STRR)。 串中发生了一些$值倍。 。 < BR>中;
}
?>

PHP手册:count_chars


  

count_chars - 返回有关字符串中使用的字符信息


I want to count the frequency of occurrences of all the letters in a string. Say I have

$str = "cdcdcdcdeeeef";

I can use str_split and array_count_values to achieve this.

array_count_values(str_split($str));

Wondering if there is another way to do this without converting the string to an array? Thanks

解决方案

You don't have to convert that into an array() you can use substr_count() to achieve the same.

substr_count — Count the number of substring occurrences

<?php
$str = "cdcdcdcdeeeef";
echo substr_count($str, 'c'); 
?>

PHP Manual

substr_count() returns the number of times the needle substring occurs in the haystack string. Please note that needle is case sensitive.

EDIT:

Sorry for the misconception, you can use count_chars to have a counted value of each character in a string. An example:

<?php
$str = "cdcdcdcdeeeef";

foreach (count_chars($str, 1) as $strr => $value) {
   echo chr($strr) . " occurred a number of $value times in the string." . "<br>";
}
?>

PHP Manual: count_chars

count_chars — Return information about characters used in a string

这篇关于算上所有的字母出现在一个字符串PHP的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆