1

I created an input text, where I write something that I want to search in an array.

I already use stristr() and stripos() but whit this I get only the same words, example:

<?php
    $value[0]= 'animals';
    //other array values

    $arrayResp = [];

    foreach($valuefounded as $value)
    {
          if(stristr($value, "animals") !== FALSE)
          {
            $arrayResp[]= $value;
          }
    }

how can I get the same result, if I type grammatical mistake like "animls"

3
  • 3
    Research "levenshtein distance" and the PHP levenshtein() Function Commented Oct 19, 2017 at 13:47
  • I do not know the scope or size of the project, but Lucene, SOLR, elasticsearch are great for this. But it's an install and learning curve so not sure if it is worth if for you. Commented Oct 19, 2017 at 13:56
  • thanks for the answer, but for my project, Levenshtein() is good enough. Commented Oct 19, 2017 at 14:41

1 Answer 1

1

There's no simple function to achieve this, but you could build something like with soundex, levenshtein or similar functions. To do so, you have to split the input text into words and do the calculation for each word.

But you should keep in mind, this works only for complete words.

function search_in_string($search, $text, $max = 2) {
    $words = explode(' ', $text);

    foreach ($words as $word) {
        if (levenshtein($word, $search) <= $max) {
            return strpos($text, $word);
        }
    }

    return false;
}
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.