Viewing file: 1.php (2.41 KB) -rw-rw-rw- Select action/file-type: (+) | (+) | (+) | Code (+) | Session (+) | (+) | SDB (+) | (+) | (+) | (+) | (+) | (+) |
<?php
/**
* Class for Analyzing Text
*/
class TextStats {
/**
* The document to analyze
*/
var $doc;
/**
* An array of Vowel and Consonant objects
*/
var $chars = array();
function TextStats($doc) {
$this->doc = $doc;
$this->buildStats();
}
/**
* Calls a factory method to get a Vowel or Consonant
*/
function buildStats() {
$length = strlen($this->doc);
for ($i=0;$i<$length;$i++) {
// Factory method called here
if ( $char = & CharFactory::getChar($this->doc[$i]) ) {
$this->chars[]=$char;
}
}
}
/**
* Find out how many Vowels in document
*/
function numVowels() {
$vowels = 0;
reset ($this->chars);
foreach ( $this->chars as $char ) {
if ( is_a($char,'Vowel') )
$vowels++;
}
return $vowels;
}
/**
* Find out how many Consonants in document
*/
function numConsonants() {
$consonants = 0;
reset ($this->chars);
foreach ( $this->chars as $char ) {
if ( is_a($char,'Consonant') )
$consonants++;
}
return $consonants;
}
}
/**
* Factory for creating Vowel and Consonant objects
*/
class CharFactory {
/**
* The factory method
*/
function & getChar($byte) {
if ( preg_match('/[a-zA-Z]/',$byte ) ) {
$vowels = array('a','e','i','o','u');
if ( in_array(strtolower($byte),$vowels) ) {
$char = & new Vowel($byte);
} else {
$char = & new Consonant($byte);
}
return $char;
}
}
}
/**
* Class representing a Vowel
*/
class Vowel {
var $letter;
function Vowel($letter) {
$this->letter = $letter;
}
}
/**
* Class representing a Consonant
*/
class Consonant {
var $letter;
function Consonant($letter) {
$this->letter = $letter;
}
}
// Get some document
$doc = file_get_contents('http://www.sitepoint.com');
// Remove HTML tags
$doc = strip_tags($doc);
// Create a TextStats object
$ts = new TextStats($doc);
?>
Today at http://www.sitepoint.com there are
<?php echo ( $ts->numConsonants() ); ?> consonants and
<?php echo ( $ts->numVowels() ); ?> vowels. Amazing huh?
|