Monday 14 July 2014

php program which reads the contents of the file and then print the Number of words, Number of chars, Number of spaces, Number of special chars, Number of digits.

 <?php  
 $datas = (file("test.txt"));  
 $word_count = 0;  
 $character_count = 0;  
 $spaces_count = 0;  
 $splchars_count = 0;  
 $digits_count = 0;  
 foreach ($datas as $array => $data) {  
   //word count  
   $word_count += str_word_count($data);  
   //character count  
   $character_count += strlen($data);  
   //spl character count  
   $spl = str_split($data);  
   foreach ($spl as $bit) {  
     if (preg_match('/[\'^£$%&*()}{@#~?><>,|=_+¬-]/', $bit)) {  
       $splchars_count += 1;  
     }  
   }  
   //numbers count  
   $num = str_split($data);  
   foreach ($num as $bit) {  
     if (preg_match('!\d+!', $bit)) {  
       $digits_count += 1;  
     }  
   }  
 }  
 $spaces_count = $word_count - 1;  
 $character_count -= $spaces_count;  
 echo 'word_count = ' . $word_count;  
 echo '--';  
 echo 'character_count = ' . $character_count;  
 echo '--';  
 echo 'spaces_count = ' . $spaces_count;  
 echo '--';  
 echo 'special_chara_count = ' . $splchars_count;  
 echo '--';  
 echo 'digits_count = ' . $digits_count;  
 ?>  

No comments:

Post a Comment