Home
Contact
Tutorials

Spell Checker

2007-10-21 15:21:00


This tutorial will show you how to create a spell checker in PHP, which can be implemented to comment forms etc. For a live example, click here The script basically consists of a form, some php which executes when the form submit button is hit, and a little css styling. The first thing we do is start all of our HTML and put in some CSS like this:


<html>
<head>
<style type="text/css">
<!--
.wrong{background-color:#FFCC99;}
-->
</style>
</head>
<body>
 


All of our php code will be located in the body section of the document, and that css simply creates a style to for incorrectly spelled words. Now we get on to the PHP coding.


<?php
        $pspell = pspell_new("en");
 


Here we simply start the php code, and load the English dictionary.


if($_POST['submit'] && $_POST['textbox']){
        $text=preg_replace("/[^a-zA-Zs]/", "", $_POST['textbox']);
 


These two lines check that the user has clicked the submit button, and has entered some text into the textbox. It then defines the variable $text which contains the text from the textbox, the preg_replace() function removes everything apart from upper and lower case letters, so that commas and other punctuation don't confuse the Pspell engine.


$parts=explode(" ",$text);
        $wrong=0;
        $print="";
 


The first line here uses the explode() function to separate each word, then add it to the array $parts so we can check each word on its own later. Then we just set up two variables which will be used later in the script.


foreach($parts as $word){
 


This starts a foreach loop, which runs through each value of the array $parts, renaming the individual value $word.


if (!pspell_check($pspell, $word)) {
                        $print=$print.' <span class="wrong">'.$word.'</span> ';
                        $wrong++;
                }else{
                        $print=$print.' '.$word.' ';
                }
 


This is the main if statement of the script, which checks to see if the word is spelled correctly, if not, it adds the word to a variable which we will output at the end of the script and highlights it, as well as adding 1 to $wrong which is effectively a counter of mistakes.


echo'< h3>You made '.$wrong.' mistake(s) which are highlighted below</h3>
                 <p>'
.$print.'</p>';
        }

?>
<form name="form1" method="post" action="">
  <p>
    <textarea name="textbox" cols="50" rows="10" id="textbox"></textarea>
</p>
  <p>
    <input name="submit" type="submit" id="submit" value="Submit">
   </p>
</form>



</body>
</html>

 


Last of all we tell the user the results of the text they inputted, then close off the if statement we started at the beginning. Finally outputting the HTML form.
Click here for the full script.
I hope you've learnt something from this that you can put to use in your own scripts.



Rate this tutorial