這裏是我想出了基於你的標題(同時使用strpos
和similar_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!';
}
我將通過拼寫檢查第一 – Jaime