Php 同时使用相似的文本和strpo

Php 同时使用相似的文本和strpo,php,Php,我想创建一个简单的搜索引擎,在用户输入中查找关键字。我知道我可以使用strpos检查字符串中是否存在单词。但是,我希望用户能够拼写错误的单词。比如说, $userInput = "What year did George Washingtin become president?"; $key_word = "Washington"; someFuntion($userInput, $key_word, $percent); if($percent > .95){ $user_searche

我想创建一个简单的搜索引擎,在用户输入中查找关键字。我知道我可以使用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函数可以这样做,或者您对如何创建这样做的函数有何建议?

您可以尝试利用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"

以下是我根据您的标题(使用
strpos
相似文本
)提出的建议,希望这些建议足以让您开始学习。这允许在短语之外进行单词搜索,并忽略标点符号:

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!';
}
函数搜索($haystack,$needle){
//删除标点符号
$haystack=preg_replace('/[^a-zA-Z 0-9]+/',''$haystack);
//寻找精确的匹配
if(条纹($haystack,$Pineder)){
返回true;
}
//寻找相似的匹配
$words=爆炸(“”,$haystack);
$total_words=计数($words);
$total_search_words=计数(爆炸(“”,$pinder));
对于($i=0;$i<$total_words;$i++){
//确保我们要搜索的字数
//不要超过剩余的字数
如果($total_words-$i)<$total_search_words){
打破
}
//一次比较x字数
$temp=内爆(“”,数组切分($words,$i,$total_search_words));
$percent=0;
类似的文本($needle,$temp,$percent);
如果($percent>=80){
返回true;
}
}
返回false;
}
$text=“乔治·华盛顿在哪一年成为总统?”;
$keyword=“华盛顿”;
如果(搜索($text$keyword)){
echo“看起来像一根火柴!”;
}

我会先通过拼写检查程序运行它,谢谢!这就是我要找的!