开发者

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

开发者 https://www.devze.com 2022-12-23 16:10 出处:网络
I want to check how many instances of the letter a appears in a certain string. 开发者_开发百科

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.


You can use the function : substr_count

Example:

$str = "I love stackoverflow";
echo substr_count($str,'o'); // prints 3


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.


substr_count($haystack, $needle);


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

$str = "I love stackovaerflowa";
print count(explode("a",$str))-1;


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

0

精彩评论

暂无评论...
验证码 换一张
取 消