在数组中搜索类似的字符串?

时间:2014-06-04 09:37:23

标签: php arrays

我有一个包含一些字符串的数组,我试图找到一个数组中存在的特定字符串,我试图使用array_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(array_search($prodInfoStr,$myArr ));

$searchRes返回2.完全没问题。

如果我搜索banana_2_4_200,结果应该返回2,以便我可以替换它。

2 个答案:

答案 0 :(得分:1)

你可以试试这个,

// 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);

我从php.net获取此代码并进行了修改。请参阅以下链接以获取更多信息

http://www.php.net/manual/en/function.levenshtein.php

答案 1 :(得分:0)

您可以为每个字符串计算Levenshtein distance,然后选择距离最小的字符串:

$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);