Number of words that start with each letter of the alphabet.

I have a text file, and I want to pull of the number of words that start with a specific letter of the alphabet. The text file has a total of something like 171,896 words that range from A-Z. Here is what I have so far as for coding. Any help would be appreciated…

[php] <?php
//reads the text file
$textfile = “wordsData.txt”;
$file = fopen("$textfile", ‘r’) or exit (“File Does not Exist!”);

// read into string
$str = file_get_contents($textfile);

// count words
//$numWords = str_word_count($str);
//echo "This file have ". $numWords . " words";

// count characters withour spaces
$str2 = ereg_replace('[[:space:]]+', '', $str);
$numChar = strlen($str2);
echo "This file have ". $numChar . " character(s) without spaces";

$string = "ab";            
$var = "a";      
if ($count = substr_count($string, $var)) {
echo $count. " matches found";
} else {
echo "match NOT found";
//$matches = null;
// $Data = fread($file, filesize($textfile));
//echo $Data;
//echo $matches;

?> [/php]

You don’t need to open the file to search it, you’re already getting the contents of the file read into an array (get_contents_file()) and you’ll want to use preg_match to find all the matching words. The example given on should work if you put your search character in the pattern ($pattern = “/^”.$search."/":wink:

do you have the exact link for that, I tried searching for some sample code that deals with this but was unable to find any, I am new to php and any additional help would be appreciated…

Sponsor our Newsletter | Privacy Policy | Terms of Service