32,000+ SUBSCRIBERS CAN'T GO WRONG !!!

phpans
GET TOP ARTICLES, SNIPPETS, SCRIPTS IN YOUR INBOX FOR FREE!

Delivered by GET EMAIL UPDATES FeedBurner
We always respect your privacy and take protecting it seriously.
We won't Spam You

Word Count In PHP

, 0,
Word Count In PHP
This tutorial is about word counter in PHP. Today I am going to discuss about this. we can count words using PHP. for that we can use PHP built in function str_word_count(). This function can detect number of word in a sentence. for an example,

<?php
$sentence = 'PHPAns Is PHP Tutorials, Scripts, Classes, Book Reviews, Jobs, Snippets, Tools, PHP Questions Answers And PHP Programmers Community';
echo 'This sentence has '. str_word_count($sentence);
?>

If you execute this code this code will execute like this,
output
This sentence has 18 Words

/attachment/2pssvqz.png

If you want you can create a function for this , then you need to create a function like this,

function wordcount($sentence)
{
$count = str_word_count($sentence);
retutn $count;
}

If we want to this function we can use it like this,
<?php
$sentence = 'PHPAns Is PHP Tutorials, Scripts, Classes, Book Reviews, Jobs, Snippets, Tools, PHP Questions Answers And PHP Programmers Community';
echo 'This sentence has '. wordcount($sentence);
?>

Output will be same. we can count words by another more way. we can count words form a sentence by using our own function. Gor that create a function name as wordcount() and writedown this code below,
<?php
function word_count($sentence)
{
$break = explode(' ',$sentence);
$count = count($break);
return $count;
}

$sentence = 'PHPAns Is PHP Tutorials, Scripts, Classes, Book Reviews, Jobs, Snippets, Tools, PHP Questions Answers And PHP Programmers Community';
echo 'This sentence has '. word_count($sentence);
?>

Now output will be same,
output
This sentence has 18 Words


we have seen three ways by that we can count word from a sentence. now we are going to create a live script, by this script we can count words. That means it's our live word counter project. For that create a index.php file first. Then write down this code into index.php file.
<?php
function word_count($sentence)
{
$break = explode(" ",$sentence);
$count = count($break);
return $count;
}

if (isset($_POST['text']))
{
$sentence = $_POST['text'];
echo $sentence .'<br/>';
echo 'This sentence have '. str_word_count($sentence) .' Words';
}
else
{
echo '<form method="post">';
echo 'Input Sentence: <br/><textarea name="text"></textarea><br/>';
echo '<input type="submit" value="count">';
echo '</form>';
}
?>


When you run this script this script will execute like this,
Word Count Demo

Yes, we have completed this script. I attached this code with this article. you can add your own styles and you can use this script anywhere.

Download PDF
Is this article helpful for you?





captcha

  • Connect
  •       
Top
Create an free account and start learning & sharing! Sign Up