php - 计算一串单词中匹配单词的百分比

标签 php regex string percentage

我有一个字符串,其中包含一堆带有空格分隔符的单词,这些单词来 self 的数据库,另一个类似的字符串包含来自用户输入的单词。

$usrKeywords = 'test1 test4 test2'; //$_POST['keywords']

$dbKeywords  = 'test1 test2 test3 test4 test5'; //from the DB

如何查看用户关键字与数据库关键字匹配的百分比?

所以对于上述情况,它将是 60%。

我知道我必须知道总共有多少个单词,然后检查 db 关键字字符串中包含多少匹配的用户关键字,然后像 3/5 * 100 这样获取百分比(对于上面的示例)。

但是在代码方面我不知道该怎么做。

最佳答案

您可以使用 array_intersect function计算这个百分比:

$usrKeywords = 'test1 test4 test2'; //$_POST['keywords']
$dbKeywords  = 'test1 test2 test3 test4 test5'; //from the DB

$arr1 = explode(' ', $usrKeywords);
$arr2 = explode(' ', $dbKeywords);

$aint = array_intersect($arr2, $arr1);

print_r($aint);
echo "percentage = " . (count($aint) * 100 / count($arr2)); // 60

关于php - 计算一串单词中匹配单词的百分比,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/24486115/

相关文章:

javascript - 正则表达式删除不需要的字符模式

swift - 计算字符串中的数字字符总数

php - 我的 MySQL 准备好的语句不起作用

php - 使用 while 循环和 mysql_fetch_array 的结果很慢

用于在具有多个句点的文件中查找文件扩展名的正则表达式

javascript - 将 Javascript RegExp 结果处理为非字符串

python - 数数没有。标记化、停用词删除和词干提取后的标记数量

c - 调整c中数组的特定单元格的大小

php - 否则 Bootstrap 警报

php - 如何在 PHP 中通过 Retrofit POST 请求发送服务器端提取请求正文