![](/img/trans.png)
[英]search through array of strings for string match from another array php
[英]search through array of strings for fuzzy string match
我有兩個數組,如下所示:
$arr1 = ("stringType1AndSomeRandomStuff",
"stringType2AndSomeRandomStuff",
"stringType3AndSomeRandomStuff",
"stringType1AndSomeRandomStuff",
"stringType2AndSomeRandomStuff",
"i don't belong here at all!",
"stringType4AndSomeRandomStuff");
在第一個數組( $arr1
)中,大多數鍵具有某種公共屬性。 在上面的示例文本中,這將是stringTypeX
。 這個“共同因素”是我需要搜索的內容。 每個字符串還有一些由AndSomeRandomStuff
例證的額外數據。
第二個數組如下所示:
$arr2 = ("stringType1" => "category1",
"stringType2" => "category2",
"stringType3" => "category3",
"stringType4" => "category4");
我需要遍歷$arr1
每個字符串,看看它是否與$arr2
中的任何鍵緊密匹配。 如果它匹配其中一個鍵,我需要來自$arr2
的鍵的值 。
如何迭代$arr1
每個字符串並確定$arr2
哪些鍵 (如果有)適用? 基本上,我需要遍歷$arr1
每個字符串並對$arr2
所有鍵執行部分匹配,以找到最接近的匹配。 想到的直接解決方案是使用兩個循環( $arr1
內容$arr1
外部, $arr2
內部為$arr2
),但PHP中是否有一個函數可以獲取字符串並查看它是否與現有字符串中的任何字符串匹配陣列? 有人知道更高效的方法嗎?
將$arr1
映射到一個函數,該函數計算$arr2
鍵的字符串編輯距離,然后返回最接近的匹配。 看看這個Levenshtein距離函數。 或者,您可以在映射函數中簡單地進行startsWith比較。
你可能會看到這樣的東西:
$stringEditDistanceThreshold = 5; // greater than this means rejected
// define the mapping function
function findClosestMatchingString($s) {
$closestDistanceThusFar = $stringEditDistanceThreshold + 1;
$closestMatchValue = null;
foreach ($arr2 as $key => $value) {
$editDistance = levenshtein($key, $s);
// exact match
if ($editDistance == 0) {
return $value;
// best match thus far, update values to compare against/return
} elseif ($editDistance < $closestDistanceThusFar) {
$closestDistanceThusFar = $editDistance;
$closestMatchValue = $value;
}
}
return $closestMatch; // possible to return null if threshold hasn't been met
}
// do the mapping
$matchingValues = array_map('findClosestMatchingString', $arr1);
您可能需要調整$stringEditDistanceThreshold
直到獲得您滿意的值。 或者你可以使用startsWith函數,這將大大簡化findClosestMatchingString
必須做的事情。
最后,這不是很有效。 它實際上是一個丑陋的嵌套循環。 你可能能夠做一些修剪或其他聰明的東西,但我懷疑如果陣列相當小,你可能不在乎。
編輯:正如@Ohgodwhy在下面的評論中所述, preg_grep可能會更好地為您服務。 在這種情況下,您的地圖功能將如下所示:
function findFirstMatchingString($s) {
$matchingKeys = preg_grep($s, array_keys($arr2));
if (!empty($matchingKeys) {
// return the value of the first match
return $arr2[$matches[0]];
}
return null;
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.