php查找正确的最近单词
正如我们所知,我们可以通过php查找正确的最近单词,php,levenshtein-distance,Php,Levenshtein Distance,正如我们所知,我们可以通过levenshtein找到最接近的单词,例如: <?php $subj = "hello world"; $str = array(); $str[] = "hallo"; $str[] = "helo"; $minStr = ""; $minDis = PHP_INT_MAX; foreach ($str as $curStr) { $dis = levenshtein($subj, $curStr); if ($dis < $minDi
levenshtein
找到最接近的单词,例如:
<?php
$subj = "hello world";
$str = array();
$str[] = "hallo";
$str[] = "helo";
$minStr = "";
$minDis = PHP_INT_MAX;
foreach ($str as $curStr) {
$dis = levenshtein($subj, $curStr);
if ($dis < $minDis) {
$minDis = $dis;
$minStr = $curStr;
}
}
echo($minStr);
我想我理解你的问题
在这里,我将主题分解,并将主题和str单词嵌套在一起。
levenhstein的返回被放置在一个数组中,首先是主题词,然后是“距离”,然后是一个子数组,其中包含所有与主题词之间的距离
$subj = "hello world";
$subj = explode(" ", "hello world");
$str = ["hallo", "helo", "aaahelojjjj", "pizza", "Manhattan"];
$minStr = "";
$minDis = PHP_INT_MAX;
foreach ($str as $curStr) {
Foreach($subj as $word){
$dis = levenshtein($word, $curStr);
$dist[$word][$dis][] = $curStr;
}
}
// optional sort keys in subarrays
foreach($dist as &$arr){
ksort($arr);
}
unset($arr);
Var_export($dist);
输出:
(unsorted)
array (
'hello' => //word
array (
1 => // $key is levenhstein output (distance from word)
array ( // values are the words that is $key distance from word
0 => 'hallo', //both these words are one from the word 'hello'
1 => 'helo',
),
8 =>
array ( // these words are 8 from 'hello'
0 => 'aaahelojjjj',
1 => 'Manhattan',
),
5 =>
array (
0 => 'pizza',
),
),
'world' => // here is how far each word is from 'world'
array (
4 =>
array (
0 => 'hallo', // both hallo and helo is 4 characters from 'world'
1 => 'helo',
),
10 =>
array (
0 => 'aaahelojjjj',
),
5 =>
array (
0 => 'pizza',
),
9 =>
array (
0 => 'Manhattan',
),
),
)
谢谢,但我认为这是不对的,基本上当我们在谷歌上用错误的词搜索时,可以找到正确的词并进行搜索,你能理解我吗?是的,我理解。但是您需要得到每个单词子数组的最低数组值。可以在不正确的单词上找到最近的而不是在不正确的单词上找到最近的,例如,当用户键入hallo
时,此解决方案必须在输出时返回hello
,对吗?就这些了,您只需自己付出一些努力!您没有在问题中表达您希望输出的内容。那我怎么知道你想要什么?最后的机会!我想我现在已经给你讲清楚了,如果这不是你想要的,那我就放弃。因为你的问题没有给我任何你想要的线索。