All about PHP/MySQL

Saturday, February 7, 2009

Remove Common Words from Search String

Before sending the user given search string to MySql, its a good idea to remove common words used in it so that it may not disturb any relevant results you have in your DB. Their are far more professional approaches out there for this task but here I am mentioning a very simple one.

Function:

function RemoveCommonWords($sText){
$CommonWords = array (
'at',
'the',
'and',
'of',
'in'
);
for ($x = 0; $x < count($CommonWords); $x++) {
$sText = str_replace(' ' . $CommonWords[$x] . ' ', ' ', $sText);
}
return $sText;
}

Usage:

$search_string = "sports shops in market";

$search_string = RemoveCommonWords($search_string);

Build your own list in the function against the variable $CommonWords.

Good Luck :)