Lets see how to code a word counter class in PHP. This class will count the number of occurrence of each word in a file. The code is simple and quite self-explanatory.
Example:
<?php
class WordCounter
{
const ASC="ascending"; //ascending order
const DESC="descending"; //descending order
private $words;
function __construct($file_name)
{
$file_words=file_get_contents($file_name);
$file_words=strtolower($file_words);
$words_array=str_word_count($file_words,1); //returning array of each words in the string
$this->words=array_count_values($words_array);
}
function count($order)
{
if($order==self::ASC)
{
asort($this->words);
}
else if($order==self::DESC)
{
arsort($this->words);
}
foreach($this->words as $key=>$value)
{
echo "{$key}-{$value}<br/>";
}
}
}
?>
Example:
$a=new WordCounter("welcome.txt");
$a->count(WordCounter::DESC);
0 Comments On This Entry
My Blog Links
Recent Entries
-
-
-
-
Word Counter Class in PHPon Apr 26 2010 03:12 AM
-
Recent Comments
Search My Blog
0 user(s) viewing
0 Guests
0 member(s)
0 anonymous member(s)
0 member(s)
0 anonymous member(s)
|
|



Leave Comment










|