How to check how many times something occurs in a string in PHP

前端 未结 5 1007
眼角桃花
眼角桃花 2020-12-19 18:56

I want to check how many instances of the letter a appears in a certain string.

What is the function for this? I need it to return an integer value.

相关标签:
5条回答
  • 2020-12-19 19:38

    substr_count is probably the most straightforward. you can also do this

    $str = "I love stackovaerflowa";
    print count(explode("a",$str))-1;
    
    0 讨论(0)
  • 2020-12-19 19:40

    I suppose substr_count could do the trick ;-)


    For example, this portion of code :

    $str = 'abcdazerty';
    echo substr_count($str, 'a');
    

    would get you the following output :

    2
    


    And, quoting :

    int substr_count  (  string $haystack  ,  
        string $needle  [,  int $offset = 0  
        [,  int $length  ]] )
    

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

    0 讨论(0)
  • 2020-12-19 19:52

    substr_count($haystack, $needle);

    0 讨论(0)
  • 2020-12-19 19:52

    you can refer to PHP string functions manual to find any function you need, http://php.net/strings

    0 讨论(0)
  • 2020-12-19 19:57

    You can use the function : substr_count

    Example:

    $str = "I love stackoverflow";
    echo substr_count($str,'o'); // prints 3
    
    0 讨论(0)
提交回复
热议问题