This tutorial about building a php script which can work as spell checker just like “Did you mean” in google search results .When you search for a misspelled word in google it shows you results with correct spelling or results with misspelled word saying did you mean “correct spelling”.For example if you search for “hostng” in google it will show “Did you mean hosting”.In this tutorial we will use levenshtein() of PHP to identify the correct word.
So let’s start the coding of a Google style Did you mean PHP script.
1).Assign all correct words in an array-You need an array which contains all possible word which you want to check for spelling.
1 2 3 |
<?php $allwords = array('facebook','orkut','twitter','yahoo', 'microsoft','paypal','google','bing','msn'); |
2).Calculate distance –Calculate the distance between input and all words using levenshtein().
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 |
$shortest = -1; foreach ($allwords as $word) { $lev = levenshtein($input, $word); if ($lev == 0) { $closest = $word; $shortest = 0; break; } if ($lev <= $shortest || $shortest < 0) { $closest = $word; $shortest = $lev; } } |
3).Display the correct word-Show the word as output for which $lev value is minimum.
1 2 3 4 5 6 7 8 9 10 11 12 13 |
if ($lev <= $shortest || $shortest < 0) { $closest = $word; $shortest = $lev; } } if ($shortest == 0) { echo ""; } else { echo "Did you mean: $closest?\n"; } } |
Here is the complete code . See Demo
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 38 39 40 41 42 43 44 45 46 47 48 |
<?php // input misspelled word //Title:A google style Did you mean PHP script $input="facebuk"; if(isset($_REQUEST['q']))$input = strtolower($_REQUEST['q']); $allwords = array('facebook','orkut','twitter','yahoo', 'microsoft','paypal','google','bing','msn'); echo 'Enter a word which is similar to these words '; foreach($allwords as $w){ echo "<b>".$w .",</b>"; } echo' <form> <input type="text" name="q" value="'.$input.'"/> <input type="submit" value="submit" /> </form> '; if(isset($input)){ $shortest = -1; foreach ($allwords as $word) { $lev = levenshtein($input, $word); if ($lev == 0) { $closest = $word; $shortest = 0; break; } if ($lev <= $shortest || $shortest < 0) { $closest = $word; $shortest = $lev; } } if ($shortest == 0) { echo ""; } else { echo "Did you mean: $closest?\n"; } } ?> |