0

I want to find frequency of all words in a given string. I wrote this code, but it is not giving correct output. Plz help

<?php
//string here
$wordsArray = "Hello world hello world this is hello world";
//echo($wordsArray);
//function here
$startPosForWord;
$endPosForWord;
$wordToMatch;
$word;
$scannedWords;
$occurance = 0;
$i;
$j;
  for($i = 0 ; $i < strlen($wordsArray); $i++)
  {
    //here we will search string for single single word
    if($wordsArray[$i] != ' ')
    {
      $wordToMatch = $wordToMatch . $wordsArray[$i];
    }
    
    //once a word is found which is delimited by a space, we will send it to find it's frequency
    else
    {
      $wordToMatch = strtolower($wordToMatch);
      //insert into scanned words array
     // echo nl2br($scannedWords." ".$wordToMatch."\n");
      if (strstr($scannedWords,$wordToMatch) == "") //this means that currently scanned word is not in our list of scanned words
      {
	$scannedWords = $scannedWords.$wordToMatch." ";
	for($j = 0 ; $j < strlen($wordsArray); $j++)
	{
	  if($wordsArray[$j] != ' ')
	  {
	    $word = $word . $wordsArray[$j];
	  }
	  else
	  {
	    $word = strtolower($word);
	    if($wordToMatch == $word)
	      $occurance ++ ;
	    $word = "";
	  }
	}
	echo nl2br("The word: ".$wordToMatch . " Occurs: ". $occurance." times and the i position is:". $i."\n");
	//clean up
	$wordToMatch = "";
	$occurance = 0;
      }
      else
      {
	$wordToMatch = "";
      }
    }
  }
  echo("scanned words are: " . $scannedWords);
?>
5
Contributors
5
Replies
7
Views
6 Years
Discussion Span
Last Post by edwinhermann
0
preg_match_all('/\b(hello|world|bla|something|else)\b/', $str, $matches);
$count = count($matches[0]);

Or something like that.

Edited by twiss: n/a

0
$words = 'Hello world hello world this is hello world';
$words = explode(' ', $words);
$frequency = array();

foreach($words as $word) {
    $word = strtolower($word);

    if(isset($frequency[$word]))
        $frequency[$word] += 1;
    else
        $frequency[$word] = 1
}

echo '<pre>'; print_r($words); echo '</pre>';
0
<?php
$str = "    Hello world hello World this is      hello world    ";
$arr=str_word_count(strtoupper($str),1);
echo "<pre>";
foreach($arr as $value)
{
	$finalarr[$value]++;
}
echo print_r($finalarr);
echo "</pre>";
?>
0
$words = 'Hello world hello world this is hello world';
$words = explode(' ', $words);
$frequency = array();

foreach($words as $word) {
    $word = strtolower($word);

    if(isset($frequency[$word]))
        $frequency[$word] += 1;
    else
        $frequency[$word] = 1
}

echo '<pre>'; print_r($words); echo '</pre>';

ok but, in case when we have an entire text file containing thousands of words, what approach can we take ?

This topic has been dead for over six months. Start a new discussion instead.
Have something to contribute to this discussion? Please be thoughtful, detailed and courteous, and be sure to adhere to our posting rules.