Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to find a similar word for a misspelled one in PHP?

I'll explain my problem:

I have a database table called country. It has two columns: ID and name.

When I want to search for 'paris', but misspelled the word: 'pares' ('e' instead of 'i'), I won't get any result from DB.

I want the the system to suggest similar words that could help in the search.

So, I am looking for help writing a script that makes suggestions from the DB that contain similar words like: paris, paredes, ... etc.

like image 901
assaqqaf Avatar asked Oct 15 '10 06:10

assaqqaf


2 Answers

In PHP you should use metaphone it is more accurate than soundex.

But your problem is getting the data from the database. You've not mentioned the DB. In MySQL you can make use of the SOUNDEX function. You just need to change your where clause in the query from

...where city = '$input_city'

to

... where soundex(city) = soundex('$input_city')

or even better you can use SOUNDS LIKE operator as

... where city sounds like '$input_city'
like image 144
codaddict Avatar answered Sep 21 '22 17:09

codaddict


soundex will return a numerical code for a word that represents its sound. Words that sound similar will have the same soundex code. You could have a table with words and their soundex codes that you could use to look up similar sounding words. You could then sort them using their levenshtein distance.

If you're looking for something simpler and you just want to handle typos in your DB queries, you can do

select * from country where city SOUNDS LIKE 'Paris' instead of select * from country where city='Paris'

like image 24
Brad Mace Avatar answered Sep 19 '22 17:09

Brad Mace