Check if strings are x% equal

我的未来我决定 提交于 2020-01-30 05:30:15

问题


I want to compare three strings:

"a text string" //target string
"a kind of similar text string"
"the cow jumps over the moon"

And set a percentage parameter that returns the results that are x% similar to the target.

$results = compare($array,$target,80)

$results // Returns an array with str 1,2, because they are at least 80 similar to the target.

Also, is a similar function possible in JavaScript or jQuery?


回答1:


In PHP, there is the function similar_text. As for JavaScript, there's the PHP.js project, which re-implements PHP functions in JavaScript. They have an implementation of similar_text you can use.

The JavaScript implementation doesn't support the percent parameter, it seems.




回答2:


The function you're looking for is similar_text.

It takes an optional 3rd parameter (passed by reference) where the percentage difference is placed.

In your situation, the following should do:

// Returns true if $str1 is at least $pct similar to $str2, otherwise false.
function compare($str1, $str2, $pct)
{
    $p = 0;
    similar_text($str1, $str2, $p);

    return ($p >= $pct);
}


来源:https://stackoverflow.com/questions/10148454/check-if-strings-are-x-equal

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!