Form and Spelling Validation -
(Page 10 of 14 )
Before we build our spell checker, let's look at the basic functionality of the pspell() functions and see how we can check individual words for spelling errors.
pspell_new ( string language ) - This function starts a spell check session. It returns a link identifier that is used by the other pspell() functions.pspell_check ( int dictionary_link, string word) - When given a word, this function will return TRUE if it is spelled correctly or FALSE if it is not.pspell_suggest ( int dictionary_link, string word) - This function will return an array populated with potential spellings of any given word.
There are a few other functions supplied by the pspell() extension, but for our purposes we won't need them. These other functions provide methods for personal wordlists and a couple of configuration options.
First off, let's look at a very basic example of how to spell check a word. We will first start a spell check session. Then we will pass a word to the pspell_check() function and examine the result we receive to determine if the word was spelled properly or not.
<?php $word = 'recieve'; $pspell_resource = pspell_new('en'); if(pspell_check($pspell_resource, $word)) { echo "'$word' is spelled correctly.<br />\n"; } else { echo "'$word' is not spelled correctly.<br />\n"; } ?> |
You will notice that we passed the string 'en' to the pspell_new() function. This identifies the language to use for spell checking. Many different languages are supported. Which dictionaries are available for your use depends on what was installed with the aspell() libraries. To obtain a list of installed dictionaries, issue the following command from a shell prompt on your server.
You can also execute the following PHP script to obtain the list of dictionaries.
<?php echo nl2br(`aspell dump dicts`); ?> |
Going to back the example code, the next thing we do is use the pspell_check() function to determine if the word stored in the $word variable is spelled correctly or not. Depending on the outcome, we display the appropriate statement.
Now, we will add in the pspell_suggest() function. This function will take a word and find other ways it could possibly be spelled. One thing to note is that this function makes no distinction between a properly spelled word and an incorrectly spelled one. It will suggest alternative spelling for any word given to it. Let's add in the suggestion functionality in the else clause.
<?php } else { echo "'$word' is not spelled correctly.<br />\n"; echo "Possible correct spellings:<br />\n"; $suggestions = pspell_suggest($pspell_resource, $word); foreach($suggestions as $suggest) { echo "$suggest<br />\n"; } } ?> |
With that addition, we now have a list of suggestions for the misspelled word. Now that we have the basics down, let's move on to our spell checking application.
Next: >>
More Miscellaneous Articles
More By Matt Wade