Creating “Do You Mean” spelling suggestion with php pspell extension

In my recent work we had requirement for creating search engine like spelling suggester. I did some research and found a quick php extension that does this easily for us. Though it has some problems some times for a few words, but usually it wont occur.

I found a php extention called pspell. Its the spelling suggester for php. Note this requires aspell library to work.

Installation

sudo apt-get install libpspell-dev 
sudo apt-get install php5-pspell
sudo apt-get install aspell-en

Once installed restart apache

sudo service apache2 restart

Sample code and test.

read comments in code for good walk through.

<?php
$pspell_link = pspell_new("en"); //load the dictionary
if (!pspell_check($pspell_link, "clokc")) { // check for work in dictionary, if not found
    $suggestions = pspell_suggest($pspell_link, "clokc"); // get suggested words

    foreach ($suggestions as $suggestion) {
        echo "Possible spelling: $suggestion<br />"; // show suggestions
    }
}
?>

For using spell suggest in sentences you can use this function below.

function spellSuggest($string)
{
    // Suggests possible words in case of misspelling
    $config_dic = pspell_config_create('en');

    // Ignore words under 3 characters
    pspell_config_ignore($config_dic, 3);

    // Configure the dictionary
    pspell_config_mode($config_dic, PSPELL_FAST);
    $dictionary = pspell_new_config($config_dic);

    // To find out if a replacement has been suggested
    $replacement_suggest = false;

    $string = explode(' ', trim(str_replace(',', ' ', $string)));// repalce any commas with spaces and explode into an array
    foreach ($string as $key => $value) {// loop through each word
        if(!pspell_check($dictionary, $value)) {// check againt existance in dictionary, if not found
            $suggestion = pspell_suggest($dictionary, $value); //add word for suggesstion

            // Suggestions are case sensitive. Grab the first one.
            if(isset($suggestion [0]) && (strtolower($suggestion [0]) != strtolower($value))) {
                $string [$key] = $suggestion [0];
                $replacement_suggest = true;
            }
        }
    }

    if ($replacement_suggest) {
        // We have a suggestion, so we return to the data.
        return implode(' ', $string);// combine the string back
    } else {
        return null;
    }
}

Usage

echo spellSuggest("This is amazingly asewome");

output:

This is amazingly awesome

Try playing around with it. leave a comment if you like it or hate it.