gpt4 book ai didi

PHP similar_text() 和 in_array() 没有像他们应该的那样工作

转载 作者:可可西里 更新时间:2023-10-31 23:21:56 26 4
gpt4 key购买 nike

我正在尝试使用 similar_text()in_array() 在 PHP 中制作一个简单的拼写检查和建议程序。我有一个文本文件 dictionary.txt,其中包含英语中的大部分单词。

首先,我将文本文件中的所有单词都换行放入一个数组中。然后在用户输入和提交时,我使用 in_array() 检查他们输入的单词是否在数组中。如果是,那么他们拼写正确。

如果不是,则我使用 similar_text() 在数组中查找与拼写错误的单词接近的单词。

我遇到了两个无法解决的问题,我相信我正在根据 PHP 文档正确使用 in_array()similar_text() .

第一个问题是,当用户键入并提交文本文件中应该也应该在数组中的单词时,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>

最佳答案

将您的添加行更改为

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

并将您的输入更改为

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

文件命令有一个讨厌的习惯,它会留下尾随的换行符,所以你可能不会基于那个进行匹配……trim 应该处理这个问题。其他更改只是为了使其不区分大小写。

关于PHP similar_text() 和 in_array() 没有像他们应该的那样工作,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/16910116/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com