gpt4 book ai didi

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

转载 作者:IT王子 更新时间:2023-10-29 00:20:17 25 4
gpt4 key购买 nike

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/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com