Spell Checking Words in a String Using PHP

Introduction

In this article I will explain spell checking of words in a string using PHP. The "Pspell_new()" function is used to open a link to the appropriate language dictionary, and the "pspell_check()" function iterates over the word list. Before using this function obtain the instructions from the PHP manual at "www.php.net/pspell".

Example1

In the following example if a word in a paragraph or sentences and words that are incorrectly spelled are indentified, then pspell_check() function returns false.

<?php

$pspell_link = pspell_new("en");

 

if (pspell_check($pspell_link, "testt")) {

    echo "This is a valid spelling";

} else {

    echo "Sorry, wrong spelling";

}

?>

The following example checks the file line by line. You can have the previous listing check a file rather than a variable for misspelled words.

Example2

Note It is important to remember that pspell_check() returns false on a numeric string.

<?php

$file = "badspelling.txt";

//check spelling open dictionary link

$dict = pspell_new("en", "british", "", "", PSPELL_FAST);

// open file

$fp = fopen ($file, 'r') or die ("Cannot open file $file");

// here read file line by line

$lineCount = 1;

while ($line = fgets($fp, 2048)) {

 // clean up trailing whitespace

 $line = trim($line);

 // check spelling of each word

 $line = preg_replace('/[0-9]+/', '', $line);

 $words = preg_split('/[^0-9A-Za-z\']+/', $line, -1,

PREG_SPLIT_NO_EMPTY);

 foreach ($words as $w) {

 if (!pspell_check($dict, $w)) {

 if (!is_array($errors[$lineCount])) {

 $errors[$lineCount] = array();

 }

 array_push($errors[$lineCount], $w);

 }

 }

 $lineCount++;

}

// close file

fclose($fp);

// if errors exist

if (sizeof($errors) > 0) {

 // print error list, with suggested alternatives

 echo "The following words were wrongly spelt: \n";

 foreach ($errors as $k => $v) {

 echo "Line $k: \n";

 foreach ($v as $word) {

 $opts = pspell_suggest($dict, $word);

 echo "\t$word (" . implode(', ', $opts) . ")\n";

 }

 }

}

?>


Similar Articles