匹配/比較文本字符串在PHP中的文本字符串比較大家好, 我試圖比較一些字符串,基本上明白,如果我有在產品飼料產品。由於來源不同,完美匹配(相同)並不是一件確定的事情。 由於產品的名稱有時會帶有或多或少的字符(iPad白色和iPad蘋果白色),我想進行一個近似匹配,也許類似於Lucene(〜)中的模糊搜索。匹配/ PHP中</p> <p>
到目前爲止,我知道並使用了preg_match和levenshtein。你能推薦任何其他方法來爲PHP的字符串做相似性匹配嗎?
匹配/比較文本字符串在PHP中的文本字符串比較大家好, 我試圖比較一些字符串,基本上明白,如果我有在產品飼料產品。由於來源不同,完美匹配(相同)並不是一件確定的事情。 由於產品的名稱有時會帶有或多或少的字符(iPad白色和iPad蘋果白色),我想進行一個近似匹配,也許類似於Lucene(〜)中的模糊搜索。匹配/ PHP中</p> <p>
到目前爲止,我知道並使用了preg_match和levenshtein。你能推薦任何其他方法來爲PHP的字符串做相似性匹配嗎?
你問是否有人有使用的想法:好吧,這是PHP
網站的一個例子,但我想它可以幫助你。
(我已經修改了代碼,可能適合的經驗,一個在您的網站):
<?php
$productString= 'Apple white IPOD';
// array of words to check against
$products = array('zen','dell laptop','apple laptop','apple black ipod',
'apple mini','Random product');
// no shortest distance found, yet
$shortest = -1;
// loop through products to find the closest product
foreach ($products as $product) {
// calculate the distance between the input word,
// and the current word
$lev = levenshtein($productString, $product);
// check for an exact match
if ($lev == 0) {
// closest word is this one (exact match)
$closest = $product;
$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 "Search product: $productString\n";
if ($shortest == 0) {
echo "Exact match found: $closest\n";
} else {
echo "Did you mean: $closest?\n";
}
?>
上面的代碼通過搜索產品,數組列表,並找到最接近的匹配。如果找到完全匹配,則使用該匹配。
謝謝埃文,你知道任何其他的字符串匹配方法嗎? –
@VictorSpinei如果您正在尋找更精確或更自定義的東西,您將不得不創建自己的功能。 –
謝謝,已經有了,我正在使用preg_match和levenshtein。仍然我喜歡這個更多的Lucene) –
那麼現在你在做什麼的問題是什麼? –