在不使用可用功能的情况下计算PHP字符串中字符出现的次数 [英] Count number of character occurrences in a string in PHP without use available function

查看:52
本文介绍了在不使用可用功能的情况下计算PHP字符串中字符出现的次数的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

很抱歉,如果该问题已经存在。
我有个问题可以帮我吗。
仅使用 strlen 函数和数组。您可以使用PHP来对字符串中字符出现的次数进行编程计数(字符不重复)。类似于创建一个新的 array_count_values 函数,该函数在php中可用。
例如:

Sorry if this question already exists. I have a question can you help me. Only use strlen function and array. Can you make programming count number of character occurrences in a string with PHP (Character not repeat). Similar to create a new array_count_values function that available in php. Eg:

$input = 'lorem lis pum';
Output: 
l appeared 2 times;
o appeared 1 times;
r appeared 1 times;
...

这是我使用可用函数时的代码array_count_values 起作用。

This is my code when using available function array_count_values and it's worked.

$a = str_split($str, 1);
foreach (array_count_values($a) as $key => $value) {
    if ($key === ' ') {
        $key = '_';
    }
    echo $key.'appeared '.$value.' times<br>';
}

感谢阅读。

推荐答案

这是一种实现方法。我敢肯定还有更简洁的方法。

This is one way to do it. I'm sure there's even more concise ways to do it.

$input = 'lorem lis pum';

for( $i = 0, $ilen = strlen( $input ), $result = array(); $i < $ilen; $i++ ) {
  $chr = $input[ $i ];
  // substituting the space with an underscore is not actually necessary
  if( $chr === ' ' ) {
    $chr = '_';
  }
  $result[ $chr ] = isset( $result[ $chr ] ) ? $result[ $chr ] + 1 : 1;
}

var_dump( $result );

您可以在线查看此示例

这篇关于在不使用可用功能的情况下计算PHP字符串中字符出现的次数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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