如何检查PHP中两个字符串的部分相似性 [英] How to check a partial similarity of two strings in PHP

查看:96
本文介绍了如何检查PHP中两个字符串的部分相似性的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

Is it any function in PHP that check the % of similarity of two strings?

例如,我有:

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

function($string1, $string2)将使我返回true,因为该行中出现了单词"how","are","you".

and the function($string1, $string2) will return me true because the words "how", "are", "you" are present in the line.

甚至更好,请给我60%的相似度,因为如何",是",您"是$string1的3/5.

Or even better, return me 60% of similarity because "how", "are", "you" is a 3/5 of $string1.

PHP中是否存在执行该功能的函数?

Does any function exist in PHP which do that?

推荐答案

由于这是一个很好的问题,我为此付出了一些努力:

As it's a nice question, I put some effort into it:

<?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中两个字符串的部分相似性的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆