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

前端 未结 4 1755
感情败类
感情败类 2020-11-27 08:14

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

相关标签:
4条回答
  • 2020-11-27 08:28

    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...

    for($i = 0; $i < strlen($s); $i++)
      if($s[i] == $c)
        echo "{$s[i]} at position $i";
    
    0 讨论(0)
  • 2020-11-27 08:31

    Can you not feed the character to preg_match_all?

    0 讨论(0)
  • 2020-11-27 08:40

    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...

    0 讨论(0)
  • 2020-11-27 08:41

    use this:

    echo substr_count("abca", "a"); // will echo 2
    
    0 讨论(0)
提交回复
热议问题