Drupal Tech Blog: 'Did you mean' in search results

11 Dec 2013

Joris Snoek - Business Dev
+31 (0)20 - 261 14 99

Our Drupal Tech blog is English, so the whole world can enjoy it :)

I think you all know the Google function, the one that makes you look stupid: the "Did you mean.....?" function. Let's call it the 'suggestion' function.

Well, in Drupal this, off course, is also possible.

If you implemented Solr, then this function is already included. But if you don't have Solr and want a low impact implementation, than this snippet may help you.

Assuming you know how to code in Drupal, and how to pass the search keys on through another function, here's a snippet that adds a suggestion if no search results where found.

This snippet queries the Drupal core search index quite heavily. So if you have a large scale Drupal installation, Solr might me a better solution.

It uses our PHP-brother: Levenshtein. Cool dude :)

* Custom function that adds suggestions to search results, when no results are found in Drupal core search index tables

function _MYMODULE_searchsuggestions($keywords) {

// Get the keywords from the search index.
$results = db_query("
FROM {search_index} s
INNER JOIN {node} n
ON s.sid = n.nid
AND n.status = 1

// Loop through the result and assign the words as string
foreach($results as $result){
$words[] = $result->word;

if(!empty($words)) {

// Loop through each word
foreach ($words as $word) {

// Check if the word is longer than 2 characters and not numeric
if (strlen($word) > 3 && !is_numeric($word) && $word != $input) {

// Use levenshteins function on the input
$match = levenshtein($input, $word);
if ($match > 0 && $match

// Put the word in the array
$array[] = $word;
// Print results, mind here that you might have a custom search page / view so URL depends on your install.
print t('Did you mean') . ':';

foreach (array_count_values($array) as $key => $value) {
return l($key, 'search', array('query' => array('keys' => $key)));


Last words

Any suggestions? Maybe you didn't know what I meant? Let me know!


Nóg meer
kennis nodig?

Check ons ons blog archief >