« Generate Numbers in PHP
OOP In PHP (Object Oriented Programming in PHP) »


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. <?php
  2.  
  3. $i=0; // number of occurrence
  4. $msg = "my name is tim tim is a dumb name i hate people named tim"; // The Sentence
  5. $word = "tim"; // Word to Search
  6.  
  7.  
  8. $txt = explode(" ", $msg); // place the sentence in an array
  9.  
  10.  
  11.  
  12. foreach ($txt as $key=>$val) {
  13.  if($val == $word) {
  14.      $i++ ;
  15.    } // end if
  16.  } // end for
  17.  
  18.  
  19. echo "The Occurrence of $word in the Sentence is : <b> $i </b> ";
  20.  
  21. ?>

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. $msg = "my name is tim tim is a dumb name i hate people named tim"; // The Sentence
  2. $msg = strtolower($msg);

Hope this answer your question ;)

Leave a Reply

You must be logged in to post a comment.