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

时间:2009-06-01 01:15:23

标签: php string

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

5 个答案:

答案 0 :(得分:37)

使用它:

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

答案 1 :(得分:0)

你能否将角色送到preg_match_all

答案 2 :(得分:0)

不确定您正在寻找什么样的回复,但这是一个可以执行此操作的功能:

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

将你正在寻找的角色和想要看的字符串传递给它:

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

它应该给你类似的东西

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

或其他......

答案 3 :(得分:0)

如果你要反复检查相同的字符串,那么为它设置某种trie甚至assoc数组是明智的,否则,直接的方法是......

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

答案 4 :(得分:0)

这对我有用。请尝试以下代码:

$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;
}
相关问题