我正在尝试在 PHP中使用similar_text()
并制作一个简单的拼写检查和建议程序。in_array()
我有一个文本文件 dictionary.txt,它是英语中的大部分单词。
首先,我将文本文件中的所有单词都放在一个新行中,放入一个数组中。然后在用户输入和提交时,我检查他们输入的单词是否在数组中,使用in_array()
. 如果是,那么他们拼写正确。
如果不是,那么我使用similar_text()
在数组中查找与拼写错误的单词接近的单词。
in_array()
我遇到了两个我无法解决的问题,我相信我正在similar_text()
根据 PHP 文档正确使用。
第一个问题是,当用户键入并提交文本文件中并且也应该在数组中的单词时,else 会触发并且不应该发生这种情况。由于它在文本文件中,它应该在数组中,并且in_array()
应该评估为真。
第二个问题是我收到一个错误,即我存储两个单词之间相似性百分比的变量similar_text()
未定义。我正在使用它,similar_text()
就像在文档注释示例中一样;实际上,我$percentageSimilarity
在每次比较之前都在重置和重新定义。为什么我收到未定义的错误?
这是我的代码:
<?php
function addTo($line){
return $line;
}
$words = array_map('addTo', file('dictionary.txt'));
if(isset($_GET['checkSpelling'])){
$input = (string)$_GET['checkSpelling'];
$suggestions = array();
if(in_array($input, $words)){
echo "you spelled the word right!";
}
else{
foreach($words as $word){
$percentageSimilarity=0.0;
similar_text($input, $word, $percentageSimilarity);
if($percentageSimilarity>=95){
array_push($suggestions, $word);
}
}
echo "Looks like you spelled that wrong. Here are some suggestions: \n";
foreach($suggestions as $suggestion){
echo $suggestion;
}
}
}
?>
<!Doctype HTMl>
<html lang="en">
<head>
<meta charset="utf-8" />
<title>Spell Check</title>
</head>
<body>
<form method="get">
<input type="text" name="checkSpelling" autocomplete="off" autofocus />
</form>
</body>
</html>