Power your Search Bar Queries for better results with PHP

Sayan Sinha
2 min readSep 14, 2021

While integrating a search box into a website or application, but do you prefer to show much relevant or better results to the users.

Most of us are dependent on the SQL ‘LIKE’ operator. Though it performs better but the results that you’re looking for is not at all relevant. Therefore most of the developers using most sophisticated algorithms to refine the query entered by the user and then that refined query is searched on database for better results.

Today, we will look into one of the such simple search refining strategy in PHP.

WORDS TO IGNORE FROM QUERY

There are words to be ignored, suppose,

“I want to see the features of Windows 11”

The above searched sentence contains 3 keywords that are useful, namely ‘features’, ‘Windows’, ‘11’.

Therefore, we can create a PHP function to filter these keywords.

function ignoreWords()
{
// You can add words as per your application niche
// like tech sites do not need words like 'I', 'an',
// 'to', 'end', 'what', etc
return [
'am', 'and', 'to', 'if', 'a', 'is', 'are', 'they',
'the', 'what', 'can', 'find', 'create', 'creating',
'see', building', 'build', 'with', 'working', 'in',
'the', 'an', 'using', 'start', 'started', 'how',
'when', 'i'
];
}

KEYWORDS TO FILTER BY USING ignoreWords()

Let’s create a function to check on search queries.

Note:- You must check for empty string and other related string sanitization before throwing the query in the function below.

function refineSearchQuery($query, $delimiter=' ')
{
$terms = array();

// Breaking the query into a words of each in array
$queries = explode($delimiter, $query);

// Search each word from queries array with the words to
// ignore from ignoreWords()
foreach($queries as $query)
{
if(!in_array(trim($query), ignoreWords()))
{
$terms[] = $query;
}
}

// returning the refined words
return $terms;
}

ENHANCING THE RESULTS RETURNED FROM DATABASE TO DISPLAY ACTUAL ONES TO USERS

After getting the result, you can compare the result query to check for contained words and select those results to display to users.

function compare2words($word1, $word2)
{
$word1 = trim(strtolower($word1));
$word2 = trim(strtolower($word2));
if(strpos($word1, $word2) !== false)
{
return true;
}
else
{
return false;
}
}

To understand:
the $word1 is a query word, and $word2 is a resultant sentence fetched from database and matched against if $word1 contains in $word2 .

The words are matched against the query keywords and searched results from database that are displayed to user.

You can further customize these functions to make it more powerful for more better matches. Hope this article been useful to you in anyway.

--

--