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

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


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'


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'


Basically you need to check similarity against a valid array of names when you got no results from your db.

My idea:

  • User searching some name
  • No exact results
  • Fetch all names from db
  • Using levenshtein calculate the most exact tip for user to return