<?php
if(isset($_POST['submit'])) {
$file = $_FILES['inputFile']['tmp_name']; //take file input
$filename = $_FILES['inputFile']['name']; //get filename
list($filename,$fileExt) = explode('.',$filename); //get file extension
if($fileExt == 'txt') { //allow only txt files
$fileContent = file_get_contents($file); //get all the contents of the file as a string
foreach(preg_split('/[\s?.!,;]/',$fileContent) as $word) { //split string to words
if(preg_match('/\bwh\w*\b/i',$word)) { //check the word starting with 'wh'
$wordWithWh[$word] = $wordWithWh[$word] + 1; //store as an array with the count of each word.
}
}
$sentence = preg_split('/([?.!])/',$fileContent,-1,PREG_SPLIT_NO_EMPTY | PREG_SPLIT_DELIM_CAPTURE); //split the sentence with .!
$question = array();
for($i = 0; $i<count($sentence);$i++) {
if($sentence[$i + 1] == '?') { //check if the sentence is a question
array_push($question,$sentence[$i]); //store the question sentence
}
}
foreach($question as $statement) {
$questionWord = preg_split('/[\s?.]/',$statement,-1,PREG_SPLIT_NO_EMPTY); //get the word starting the question
$questionWithWord[$questionWord[0]] = $questionWithWord[$questionWord[0]] + 1; //store the word with the count
}
}else {
echo 'Only Text File with extension .txt is allowed'; //error message if the file uploaded is not txt.
}
}
?>
<form method="POST" name="regTest" enctype="multipart/form-data">
<input type="file" name="inputFile">
<input type="submit" name="submit" value="Submit">
</form>
<?php
if(!empty($wordWithWh)) {
echo 'Word Count Starts with wh' .'<br>';
foreach($wordWithWh as $key => $value) {
echo $key .' :' . $value .'<br>';
}
}
if(!empty($questionWithWord)) {
echo '<br> Question Starts with <br>';
foreach($questionWithWord as $key => $value) {
echo $key .' :' . $value . '<br>';
}
}
?>