Calculating average word length : preg_split « String « PHP






Calculating average word length

 
<?php
$word_count = $word_length = 0;

if ($fh = fopen('novel.txt','r')) {
  while (! feof($fh)) {
    if ($s = fgets($fh)) {
      $words = preg_split('/\s+/',$s,-1,PREG_SPLIT_NO_EMPTY);
      foreach ($words as $word) {
        $word_count++;
        $word_length += strlen($word);
      }
    }
  }
}

print sprintf("The average word length over %d words is %.02f characters.",
              $word_count,
              $word_length/$word_count);
?>
  
  








Related examples in the same category

1.preg_split() Flags
2.preg_split() function operates like split(), except that regular expressions are accepted as input parameters for pattern.
3.preg_split.php
4.Discarding empty elements with preg_split()
5.How preg_split() can be used:
6.Limiting the number of returned elements with preg_split()
7.Parsing a date with preg_split()
8.Using preg_split()
9.Using preg_split() to Break Up Strings