PHP 相似词使用带有数组的 soundex


PHP Similar Words using soundex with array

我正在创建一个findSpellings函数,该函数有两个参数$word和$allWords。 $allwords是一个数组,其中包含单词拼写错误,听起来可能类似于$word变量。我试图完成的是基于 soundex 函数打印出所有与$word相似的单词。我在打印带有单词的数组时遇到问题。我的功能如下。任何帮助将不胜感激:

<?php 
$word = 'stupid';
$allwords = array(
    'stupid',
    'stu and pid',
    'hello',
    'foobar',
    'stpid',
    'supid',
    'stuuupid',
    'sstuuupiiid',
);
function findSpellings($word, $allWords){
while(list($id, $str) = each($allwords)){
    $soundex_code = soundex($str);
    if (soundex($word) == $soundex_code){
        //print '"' . $word . '" sounds like ' . $str;
        return $word;
        return $allwords;
    }
    else {
        return false;
    }
}
 }
 print_r(findSpellings($word, $allWords));
?>
if (soundex($word) == $soundex_code){
    //print '"' . $word . '" sounds like ' . $str;
    return $word;
    return $allwords;
}

您不能有 2 个返回,第一个返回将退出代码。

你可以做这样的事情:

if (soundex($word) == $soundex_code){
    //print '"' . $word . '" sounds like ' . $str;
    $array = array('word' => $word, 'allWords' => $allWords);
    return $array;
}

然后只需从$array中检索值,如下所示:

$filledArray = findSpellings($word, $allWords);
echo "You typed".$filledArray['word'][0]."<br/>";
echo "Were you looking for one of the following words?<br/>";
foreach($filledArray['allWords'] as $value)
{
    echo $value;
}