Php 在数组中搜索相似的字符串?
我有一个包含一些字符串的数组,我试图找到数组中存在的特定字符串,我试图使用数组_search()它正在工作,但它正在搜索精确的字符串,是否有任何方法可以找到类似的字符串并返回其位置。下面是我的例子Php 在数组中搜索相似的字符串?,php,arrays,Php,Arrays,我有一个包含一些字符串的数组,我试图找到数组中存在的特定字符串,我试图使用数组_search()它正在工作,但它正在搜索精确的字符串,是否有任何方法可以找到类似的字符串并返回其位置。下面是我的例子 $prodInfoStr = 'banana_2_3_150'; $myArr = Array ( [0] => apple_3_1_180 [1] => apricot_4_100_65 [2] => banana_2_3_135 ); $searchRes = trim(arra
$prodInfoStr = 'banana_2_3_150';
$myArr = Array ( [0] => apple_3_1_180 [1] => apricot_4_100_65 [2] => banana_2_3_135 );
$searchRes = trim(array_search($prodInfoStr,$myArr ));
$searchRes
返回2。非常好
如果我搜索香蕉2\u 4\u 200,结果应返回我2,以便我可以替换它。您可以为每个字符串计算a,然后选择距离最小的字符串:
$myArr = Array ( 'apple_3_1_180', 'apricot_4_100_65', 'banana_2_2.5_135' );
$prodInfoStr = 'banana_2_3_150';
$scores = array();
foreach($myArr as $item)
$scores[$item] = levenshtein($item, $prodInfoStr);
asort($scores);
echo "the most similar string is ", key($scores);
你可以试试这个
// input word
$input = 'banana_2_3_150';
// array of words to check against
$words = array('apple_3_1_180','apricot_4_100_65','banana_2_2.5_135');
// no shortest distance found, yet
$shortest = -1;
// loop through words to find the closest
foreach ($words as $word) {
// calculate the distance between the input word,
// and the current word
$lev = levenshtein($input, $word);
// check for an exact match
if ($lev == 0) {
// closest word is this one (exact match)
$closest = $word;
$shortest = 0;
// break out of the loop; we've found an exact match
break;
}
// if this distance is less than the next found shortest
// distance, OR if a next shortest word has not yet been found
if ($lev <= $shortest || $shortest < 0) {
// set the closest match, and shortest distance
$closest = $word;
$shortest = $lev;
}
}
echo "Matched Key =>" . array_search($closest,$words);
//输入字
$input='BANANAN_2_3_150';
//要检查的单词数组
$words=array('apple_3_1_180'、'apricot_4_100_65'、'banana_2_2.5_135');
//还没有找到最短的距离
$shortest=-1;
//通过单词循环找到最接近的单词
foreach($words作为$word){
//计算输入字之间的距离,
//那么现在这个词呢
$lev=levenshtein($input,$word);
//检查是否完全匹配
如果($lev==0){
//最接近的单词是这个(完全匹配)
$closest=$word;
$shortest=0;
//打破循环;我们找到了一个完全匹配的
打破
}
//如果此距离小于找到的下一个最短距离
//距离,或者如果尚未找到下一个最短单词
如果你对“相似字符串”的定义是什么在你的$myArr
中,我看不到香蕉2\u 3\u 150
如果搜索香蕉2\u 3\u 150应该返回2,类似的意思是起始字母应该匹配。如果搜索苹果4\u 100\u 65
,它应该返回什么?它应该返回杏子4\u 100\u 65
还是苹果3\u 1\u 180
?应该返回苹果3\u 1\u 180