Occurrence of a word in a sentence using php
Posted by chaabant on Jan 9, 2008
Can someone please post a code that will return a number of how many instances of a string are in a string? For example:
“my name is tim tim is a dumb name i hate people named tim”
I want a code to return “3″ (for the 3 instances of tim) for that. Please help!
here is the code :
-
<?php
-
-
$i=0; // number of occurrence
-
$msg = "my name is tim tim is a dumb name i hate people named tim"; // The Sentence
-
$word = "tim"; // Word to Search
-
-
-
-
-
-
foreach ($txt as $key=>$val) {
-
if($val == $word) {
-
$i++ ;
-
} // end if
-
} // end for
-
-
-
echo "The Occurrence of $word in the Sentence is : <b> $i </b> ";
-
-
?>
Result :
The Occurrence of tim in the Sentence is : 3
Take note that in php there is a difference when using a capital letter , Tim is Different than tim ; A Solution for this would be to use the string strtolower ( string $str ) function .
in our case :
-
$msg = "my name is tim tim is a dumb name i hate people named tim"; // The Sentence
Hope this answer your question ![]()