4

我正在尝试在 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>
4

2 回答 2

3

将添加到行更改为

function addTo($line){
    return strtolower(trim($line));
}

并将您的输入更改为

$input = strtolower(trim($_GET['checkSpelling']));

file 命令有一个讨厌的习惯,即留下尾随的换行符,因此您可能不会基于此进行匹配……修剪应该注意这一点。其他更改只是为了使其不区分大小写。

于 2013-06-04T05:11:16.887 回答
1

When you use file(), each element of $words will still have the newline character appended to it. You can remove it by using FILE_IGNORE_NEW_LINES:

$words = file('dictionary.txt', FILE_IGNORE_NEW_LINES);

You could also normalize the needle by applying strtolower(), assuming all your dictionary items are already lowercase:

if (!($input = filter_input(INPUT_GET, 'checkSpelling', FILTER_UNSAFE_RAW))) {
    die("Bad input, probably");
}
$input = strtolower($input);

This is because in_array() doesn't match in a case insensitive manner; e.g. "Hello" != "hello".

Further normalization could include removing anything non-wordy from your words.

于 2013-06-04T05:20:57.897 回答