tags:

views:

85

answers:

2

Hello there,

I completely have no idea how to do this as I am not a regexp expert..

But I wanted to search and count a specified CASE-INSENSITIVE text in a long string, for example:

the function:

int count_string ( string $string_to_search, string $input_search )

example usage and result:

$my_string = "Hello my name is John. I love my wife, child, and dog very much. My job is a policeman.";

print count_string("my", $my_string); // prints "3"
print count_string("is", $my_string); // prints "2"

Is there any built-in function to do this?

Any kind of help would be appreciated :)

+7  A: 

substr_count() is what you are looking for.

substr_count(strtolower($string), strtolower($searchstring)) would make the count insensitive. (courtesy of gnarf)

Michael
To make it case insensitive: substr_count(strtolower($haystack), strtolower($needle)) should suffice
gnarf
Thanks gnarf, edited
Michael
+2  A: 

preg_match_all() returns a number of matches for a regular expression - rewriting your examples:

 echo preg_match_all("/my/i", $my_string, $matches);
 echo preg_match_all("/is/i", $my_string, $matches);

Although - preg_match_all is a bit overkill for a simple substring search - it may be more useful say if you wanted to count the number of numbers in a string:

 $my_string = "99 bottles of beer on the wall, 99 bottles of beer\n";
 $my_stirng .= "Take 1 down pass it around, 98 bottles of beer on the wall\n";

 // echos 4, and $matches[0] will contain array('99','99','1','98');
 echo preg_match_all("/\d+/", $my_string, $matches);

For the simple substrings use substr_count() as suggested by Michael - if you want case insensitive just strtolower() both arguments first.

gnarf