2

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 :)

2 Answers 2

9

substr_count() is what you are looking for.

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

Sign up to request clarification or add additional context in comments.

Comments

2

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.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.