查找与数组php最近的匹配字符串
我有一个保存在var中的字符串值,我想将它与数组进行比较,并打印最接近的匹配数组号,同时区分大小写 因此,问题是如何在数组中找到与var查找与数组php最近的匹配字符串,php,arrays,preg-match,Php,Arrays,Preg Match,我有一个保存在var中的字符串值,我想将它与数组进行比较,并打印最接近的匹配数组号,同时区分大小写 因此,问题是如何在数组中找到与var$bio最近的匹配项,在这种情况下,它将是4 我看过pregmatch,但不确定在这种情况下如何使用它 我有代码 <?php $bio= "Tom, male, spain"; $list= array( 1 => array("Tom", "male", "UK"), 8 => array("bob", "Male", "s
$bio
最近的匹配项,在这种情况下,它将是4
我看过pregmatch,但不确定在这种情况下如何使用它
我有代码
<?php
$bio= "Tom, male, spain";
$list= array(
1 => array("Tom", "male", "UK"),
8 => array("bob", "Male", "spain"),
4 => array("Tom", "male", "spain"),
9 => array("sam", "femail", "United States")
);
function best_match($bio, $list)
{
}
这可能是一份工作,即:
另一种使用
输出:
Best match is at index: 4 with score: 3
最接近的匹配基于什么?好点我会更新问题这看起来很有希望,谢谢我会尽快尝试接受答案
$bio= "Tom, male, spain";
$list = array(
1 => array("Tom", "male", "UK"),
8 => array("bob", "Male", "spain"),
4 => array("Tom", "male", "spain"),
9 => array("sam", "femail", "United States")
);
$percent_old = 0;
foreach ($list as $key => $value ) # loop the arrays
{
$text = implode(", ", $value); # implode the array to get a string similar to $bio
similar_text($bio, $text, $percent); # get a percentage of similar text
if ($percent > $percent_old) # check if the current value of $percent is > to the old one
{
$percent_old = $percent; # assign $percent to $percent_old
$final_result = $key; # assign $key to $final_result
}
}
print $final_result;
# 4
$bio= "Tom, male, spain";
$list= array(
1 => array("Tom", "male", "UK"),
8 => array("bob", "Male", "spain"),
4 => array("Tom", "male", "spain"),
9 => array("sam", "femail", "United States")
);
function best_match($bio, $list) {
$arrbio = explode(', ', $bio);
$max = 0;
$ind = 0;
foreach($list as $k => $v) {
$inter = array_intersect($arrbio, $v);
if (count($inter) > $max) {
$max = count($inter);
$ind = $k;
}
}
return [$ind, $max];
}
list($index, $score) = best_match($bio, $list);
echo "Best match is at index: $index with score: $score\n";
Best match is at index: 4 with score: 3