2016-10-27 3 views
3

사용자 입력에서 키워드를 찾는 간단한 검색 엔진을 만들고 싶습니다. 문자열에 문자열이 있는지 확인하기 위해 strpos를 사용할 수 있습니다. 그러나 사용자가 잘못된 단어를 철자하게 할 수 있기를 바랍니다. 예를 들어, similar_text와 strpos를 함께 사용하기

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

이 작업을 수행하거나 수행하는 함수를 작성하는 방법에 대한 제안을 않는 PHP 함수가 있나요?

+1

먼저 맞춤법 검사기를 통해 실행합니다. – Jaime

답변

3

PHP의 표준 라이브러리에서 levenshtein 기능을 활용 해보십시오. 설명서의 몇 가지 예를 보려면 여기를 참조하십시오. http://php.net/manual/en/function.levenshtein.php

그러나 가능한 키워드 목록이 커지면 매우 비싼 계산이 될 수 있습니다.

편집 : 최소 가능한 예 : 여기

<?php 

$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" 
+0

감사합니다! 이것은 내가 찾고 있었던 것이다! – John

2

내가 제목에 따라 희망 시작하기에 충분해야한다, (모두 strpossimilar_text 사용) 해낸 것입니다. 이렇게하면 구뿐만 아니라 한 단어 검색도 허용되며 구두점은 무시됩니다.

function search($haystack, $needle) { 
    // remove punctuation 
    $haystack = preg_replace('/[^a-zA-Z 0-9]+/', '', $haystack); 

    // look for exact match 
    if (stripos($haystack, $needle)) { 
     return true; 
    } 

    // look for similar match 
    $words = explode(' ', $haystack); 
    $total_words = count($words); 
    $total_search_words = count(explode(' ', $needle)); 
    for ($i = 0; $i < $total_words; $i++) { 
     // make sure the number of words we're searching for 
     // don't exceed the number of words remaining 
     if (($total_words - $i) < $total_search_words) { 
      break; 
     } 

     // compare x-number of words at a time 
     $temp = implode(' ', array_slice($words, $i, $total_search_words)); 
     $percent = 0; 
     similar_text($needle, $temp, $percent); 
     if ($percent >= 80) { 
      return true; 
     } 
    } 

    return false; 
} 

$text = "What year did George Washingtin become president?"; 
$keyword = "Washington"; 

if (search($text, $keyword)) { 
    echo 'looks like a match!'; 
}