«
»


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 :

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
<?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
 
 
$txt = explode(" ", $msg); // place the sentence in an array
 
 
 
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> ";
 
?>
<?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

$txt = explode(" ", $msg); // place the sentence in an array

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 :

1
2
$msg = "my name is tim tim is a dumb name i hate people named tim"; // The Sentence
$msg = strtolower($msg);
$msg = "my name is tim tim is a dumb name i hate people named tim"; // The Sentence
$msg = strtolower($msg);

Hope this answer your question ;)

Leave a Reply

You must be logged in to post a comment.