简体   繁体   English

计算PHP字符串中某个特定字符的所有出现次数的最有效方法是什么?

[英]What is the most efficient way to count all the occurrences of a specific character in a PHP string?

计算PHP字符串中某个特定字符的所有出现次数的最有效方法是什么?

用这个:

echo substr_count("abca", "a"); // will echo 2

您不能将字符提供给preg_match_all吗?

Not sure what kind of a response you're looking for, but here's a function that might do it: 不知道您要寻找哪种响应,但是下面的函数可以做到:

function findChar($c, $str) {
    indexes = array();
    for($i=0; $i<strlen($str); $i++) {
        if ($str{$i}==$c) $indexes[] = $i;
    }
    return $indexes;
}

Pass it the character you're looking for and the string you want to look: 将您要查找的字符和想要查找的字符串传递给它:

$mystring = "She shells out C# code on the sea shore";
$mychar = "s";
$myindexes = $findChar($mychar, $mystring);
print_r($myindexes);

It should give you something like 它应该给你类似的东西

Array (
    [0] => 0
    [1] => 4
    [2] => 9
    [3] => 31
    [4] => 35
)

or something... 或者其他的东西...

If you are going to be repeatedly checking the same string, it'd be smart to have some sort of trie or even assoc array for it otherwise, the straightforward way to do it is... 如果您要反复检查同一字符串,那么为它准备某种特里或者甚至assoc数组将是明智的,否则,这样做的简单方法是...

for($i = 0; $i < strlen($s); $i++)
  if($s[i] == $c)
    echo "{$s[i]} at position $i";

This was working for me. 这为我工作。 Please try below code : 请尝试以下代码:

$strone = 'Sourabh Bhutani';
$strtwo = 'a';
echo parsestr($strone, $strtwo);

function parsestr ($strone, $strtwo) {
$len = 0;
while ($strtwo{$len} != '') {
    $len++;
}

$nr = 0;

while ($strone{$nr} != '')
{
    if($strone{$nr} != ' ')
    {
        $data[$nr] = $strone{$nr};
    }
    $nr++;
}

$newdata = $data;

if($len > 1)
{
    $newdata = array();
    $j = 0;
    foreach($data as $val)
    {
        $str .= $val;
        if($j == ($len -1))
        {
            $newdata[] = $str;
            $str = '';
            $j = 0;
        }
        else
            $j++;
    }
}
$i = 0;

foreach ($newdata as $val) {
    if($val == $strtwo)
    {
        $i++;
    }
}
return $i;
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM