Write a PHP Program to count number of words from a file.
PHP program to count number of words in a string with its number of occurrences.
First of all Create the interface where user can enter text or string to count the number of words and its frequencies.Here is index.php file.
<head>
<style>
#textarea{
width:100%;
min-height:100px;
margin-bottom:50px;
}
#count,#clear{
float:right;
width:200px;
height:50px;
box-shadow:1px 2px 2px 1px green ;
background:#9999CC;
color:white;
font-size:13px;
margin-right:10px;
}
#count:hover, #clear:hover{
box-shadow:1px 2px 2px 1px black ;
margin-top:-2px;
font-size:14px;
}
</style>
</head>
<body>
<p>Enter your texts here.</p>
<textarea id="textarea" placeholder="Put Your Text here to Count Your words."></textarea>
<input type="reset" value="Clear" id="clear"/ >
<input type="submit" value="Count" id="count"/ >
<p id="result"></p>
<script type="text/javascript" src="main.js"></script>
<script type="text/javascript">
$(document).ready(function(){
$("#count").on("click",function(){
var strings = $("#textarea").val();
if(strings=="")
{
$("#result").text("Please put some text to count words");
}
else
{
$.ajax({
type:"POST",
url:"countwords.php",
data:{strings:strings}
}).done(function(msg){
//alert(msg);
$("#result").html(msg);
});
}
});
$("#clear").on("click",function(){
$("#textarea").val("");
});
});
</script>
</body>
Here is the countwords.php file.
<?php
/*This program Counts the number of words in a given File and its number of occurence*/
class WordCounter{
const ASC=1;
const DSC = 2;
private $words;
function __construct()
{
$file_content = $_POST['strings'];
//str_word_count counts words inside a string and returns in array format
//array_count_values counts the number of each values in the array
$this->words = (array_count_values(str_word_count(strtolower($file_content),1)));
}
public function counting($order)
{
if($order==self::ASC)
asort($this->words);
else if($order==self::DSC)
arsort($this->words);
foreach($this->words as $key=>$val)
{
echo $key."=". $val."<br/>";
}
}
}
?>
<br/>
<?php
$var = new WordCounter();
$var->counting(WordCounter::ASC);
?>
0 comments:
Feel free to contact the admin for any suggestions and help.