Hello readers, today we are going to write a custom PHP program to count the number of words in a string, Although PHP has its own function to count the number of words which is, str_word_count(), the intention of writing this custom PHP script is to teach the basic functionalities to the new PHP learners. Especially for the school / college students who wants to learn PHP basics.
Here is the script:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 |
<?php if(isset($_POST['submit'])){ //get the string $string = $_POST['string']; $word_count = 0; //check if the string is not empty then allow it if(!empty($string)){ print $string."<br><br>"; //lets remove special characters and numbers and keep only A to Z and a to z $string_only_alphabets = preg_replace("/[^A-za-z]/", " ", $string); //remove unwanted space between words $string_only_single_space = preg_replace("/\s+/", " ", $string_only_alphabets); $word_count = count(explode(' ', trim($string_only_single_space))); } print "Sentence has <b>$word_count</b> word(s)!"; } ?> <html> <body> <h2>Custom PHP program to count the number of words in a string.</h2> <form action="" method="post"> <h3>Write a sentence</h3> <textarea name="string"></textarea><br /><br /> <button name="submit" type="submit">Find Words!</button> </form> </body> </html> |
Just read the comments in the above program to understand each line of the script. Basically the above PHP script will remove unwanted spaces between the words and count only the words other than numbers and special characters.
You can see the demo of this above script here:
very good coding in any language, it is easy to understand.
can you please help me i dnt get the correct output?