Implement Google Style “Did you mean?” Feature in PHP


In this article, we will add our own “Did you mean” feature in PHP. For this, we will implement Smith-Waterman Gotoh Algorithm. We will get the search term input by the user and compare it with the array list of titles. The highest match will be returned. In short, get input search term and title, compare two strings in PHP, and returned accordingly.

Before we deep dive into this feature, it’s good to my previous articles about How to Compare Similarity Between Two Strings in PHP?

A little knowledge about Smith-Waterman Gotoh Algorithm. Instead of looking at the entire sequence, the Smith–Waterman algorithm compares segments of all possible lengths and optimizes the similarity measure. This algorithm uses the complexity of O(mn) where m and n are length of strings.

We will implement this feature in searching posts in WordPress. When no posts are found, but we will search the titles and returned the most matched two titles. I have written comments to make the code understandable. First of all, we will get the list of articles and stores the title of posts in an array titles.

As you can see, I have all the post titles stored in an array titles[]. I get the post titles in WordPress BUT YOU CAN GET IT DONE IN ANY FRAMEWORK, CMS OR LANGUAGE. So, if you are using another framework like CI, Laravel, or any other, you can simply get the titles and store them in an array titles[]. Every other process is the SAME.

Another step after getting the titles of posts is to get the search input and process accordingly. In this article, we will display TWO most matched content. We will store these values in variables $temp_first and $temp_second. Similarly, if you want to display the matched percentage, we can store it in $first_match_percent and $second_match_percent.

We implement two classes SmithWatermanGotoh and SmithWatermanMatchMismatch. Now, our complete code looks like below:

Read More Articles


Please enter your comment!
Please enter your name here

This site uses Akismet to reduce spam. Learn how your comment data is processed.