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
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
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_second. Similarly, if you want to display the matched percentage, we can store it in
We implement two classes
SmithWatermanMatchMismatch. Now, our complete code looks like below: