php - 如何在 PHP 中检查两个字符串的部分相似性

标签 php string

PHP 中是否有任何函数可以检查两个字符串的相似度百分比?

例如我有:

$string1="Hello how are you doing" 
$string2= " hi, how are you"

function($string1, $string2) 将返回 true,因为行中出现了单词“how”、“are”、“you”。

或者更好,返回 60% 的相似度,因为“how”、“are”、“you”是 $string1 的 3/5。

PHP 中是否存在执行此操作的函数?

最佳答案

因为这是一个很好的问题,所以我付出了一些努力:

<?php
$string1="Hello how are you doing";
$string2= " hi, how are you";

echo 'Compare result: ' . compareStrings($string1, $string2) . '%';
//60%


function compareStrings($s1, $s2) {
    //one is empty, so no result
    if (strlen($s1)==0 || strlen($s2)==0) {
        return 0;
    }

    //replace none alphanumeric charactors
    //i left - in case its used to combine words
    $s1clean = preg_replace("/[^A-Za-z0-9-]/", ' ', $s1);
    $s2clean = preg_replace("/[^A-Za-z0-9-]/", ' ', $s2);

    //remove double spaces
    while (strpos($s1clean, "  ")!==false) {
        $s1clean = str_replace("  ", " ", $s1clean);
    }
    while (strpos($s2clean, "  ")!==false) {
        $s2clean = str_replace("  ", " ", $s2clean);
    }

    //create arrays
    $ar1 = explode(" ",$s1clean);
    $ar2 = explode(" ",$s2clean);
    $l1 = count($ar1);
    $l2 = count($ar2);

    //flip the arrays if needed so ar1 is always largest.
    if ($l2>$l1) {
        $t = $ar2;
        $ar2 = $ar1;
        $ar1 = $t;
    }

    //flip array 2, to make the words the keys
    $ar2 = array_flip($ar2);


    $maxwords = max($l1, $l2);
    $matches = 0;

    //find matching words
    foreach($ar1 as $word) {
        if (array_key_exists($word, $ar2))
            $matches++;
    }

    return ($matches / $maxwords) * 100;    
}
?>

关于php - 如何在 PHP 中检查两个字符串的部分相似性,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/16520646/

相关文章:

php - 将 javascript var 转移到 php var?

php - 如何使用键查找数组/字典值?

php - 我在哪里可以找到 GD 兼容字体?

python - 使用python在一行中的一组字符之前添加一个新行

C++:我用不同的位置两次调用一个字符串 substr,转换为 const char *,它们返回相同,为什么?

c++ - stringstream、string 和 char* 转换混淆

javascript - 从数组的数字元素创建 HTML 表格

javascript - 在获取 api 中使用 header 时不允许使用 405 方法

string - Haskell 提取字符串中的子字符串

java - 循环不会多次迭代 if 语句