Word Count In PHP

  • Author: Sajjad Hossain
  • |
  • Added: Apr 29, 2016
  • |
  • In: PHP Snippets

This tutorial is about word counter in PHP. Today I am going to discuss 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

attachment2pssvqzpng

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);
?>
The output will be same. we can count words by another more way. we can count words form a sentence by using our own function. For that create a function name as wordcount() and write down 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.

Search
I am...

Sajjad Hossain

I have five years of experience in web development sector. I love to do amazing projects and share my knowledge with all.

NEED HOSTING?
Are you searching for Good Quality hosting?
You can Try It!
Connect Social With PHPAns
Top