Ryan Claxton Ryan Claxton - 2 months ago 6
PHP Question

php string search from large array for page filter

Basically I have a huge array of possibilities that could be for example sports teams or sport names:

Toronto Maple Leafs
New Jersey Devils
Boston Red Socks
Hockey
Soccer
etc...

So I have a search bar where the user can type in anything they want.. I need a way to take what they enter in compare it to the array and if it is a close enough match add it to a filter variable.

example:

if (strpos($userSearch, 'Hockey') !== false) {
$pageVar = $pageVar . "+" . "Hockey";
}


Doing it this way ^ has some set backs one lets say someone enters hockie or something like that.. or Toronto instead of Toronto maple leafs.. without going through all the possible cases one by one there must be a better way..

Thanks

Answer

For an exact match, you can use in_array()

$input = 'carrrot';
$words  = array('apple','pineapple','banana','orange','radish','carrot','pea','bean','potato');    
if (in_array($words, $input)) {
    echo "$input was found in array\n";
}

For similar match, you can try levenshtein() (first example on php doc page)

$input = 'carrrot';
$words  = array('apple','pineapple','banana','orange','radish','carrot','pea','bean','potato');
$shortest = -1;
foreach ($words as $word) {
    $lev = levenshtein($input, $word);
    if ($lev == 0) {
        $closest = $word;
        $shortest = 0;
        break;
    }
    if ($lev <= $shortest || $shortest < 0) {
        $closest  = $word;
        $shortest = $lev;
    }
}
echo "Input word: $input\n";
if ($shortest == 0) {
    echo "Exact match found: $closest\n";
} else {
    echo "Did you mean: $closest?\n";
}

Result:

Input word: carrrot
Did you mean: carrot?

also for similar match, you can try similar_text()

$input  = 'iApple';
$words = array('apple','pineapple','banana','orange','radish','carrot','pea','bean','potato');
$shortest = 70;
foreach ($words as $word) {
    similar_text($word, $input, $percent);   
    $percent = round($percent);
    if ($percent == 100) {
        $closest = $word;
        $shortest = 100;
        break;
    }
    if ($percent >= $shortest) {
        $closest  = $word;
        $shortest = $percent;
    }  
}
echo "Input word: $input\n";
if ($shortest == 100) {
    echo "Exact match found: $closest\n";
} else {
    echo "Did you mean: $closest?\n";
}

Result:

Input word: iApple
Did you mean: apple?

To achieve good results you can use a combination of levenshtein(), similar_text(), and soundex()

Comments