John John - 1 year ago 87
PHP Question

Using similar_text and strpos together

I want to create a simple search engine that looks for key words in a users input. I know I can use strpos to check if a word exists in the string. However, I want the users to be able to spell the word wrong. For example,

$userInput = "What year did George Washingtin become president?";
$key_word = "Washington";
someFuntion($userInput, $key_word, $percent);
if($percent > .95){
$user_searched_washington = True;

Is there any php function that does this, or do you have suggestions on how to create a function that does?

Answer Source

You could try to leverage the levenshtein functionality in PHP's standard library. See here for some examples in the documentation:

However, this might become a very expensive calculation when your list of possible keywords grows.

EDIT: a minimum viable example:


$myInput = 'persident';
$possibleKeywords = ['tyrant', 'president', 'king', 'royal'];
$scores = [];

foreach ($possibleKeywords as $keyword) {
    $scores[] = levenshtein($myInput, $keyword);

echo $possibleKeywords[array_search(min($scores), $scores)];
// prints: "president"