similar_text()函数是PHP中的内置函数。此函数计算两个字符串的相似度,并返回两个字符串中匹配字符的数量。该函数的作用是找到最长的第一个公共子字符串,然后递归地对前缀和后缀重复此操作。返回所有公共子字符串的长度总和。
它还可以百分比形式计算两个字符串的相似度。该函数将结果除以给定字符串长度的平均值乘以100,以百分比形式计算相似度。
用法:
similar_text( $string1, $string2, $percent)
参数:此函数接受上述语法中所示的三个参数,其中必须提供前两个参数,最后一个是可选参数。所有这些参数如下所述:
$string1,$string2:这些强制性参数指定要比较的两个字符串
$percent :此参数是可选的。它以百分比形式指定用于存储相似性的变量名称。通过将引用作为第三个参数传递,该函数将计算相似性百分比。
返回值:它返回两个字符串之间的匹配字符数。
例子:
Input : $string1 = "code", $string2 = "coders"
Output : 4 (80 %)
Input : $string1 = "hackers", $string2 = "hackathons"
Output : 5 (58.823529411765 %)
以下示例程序旨在说明similar_text()函数:
程序1:
$sim = similar_text("hackers", "hackathons", $percent);
// To display the number of matching characters
echo "Number of similar characters : $sim\n";
// To display the percentage of matching characters
echo "Percentage of similar characters : $percent\n";
?>
输出量
Number of similar characters : 5
Percentage of similar characters : 58.823529411765>
程序2:该程序将突出显示该功能的区分大小写。
$output = similar_text("geeks for geeks",
"Geeks for Geeks", $percent);
// To display the number of matching characters
echo "Number of similar characters : $output\n";
// To display the percentage of matching characters
echo "Percentage of similar characters : $percent\n";
?>
输出:
Number of similar characters : 13
Percentage of similar characters : 86.666666666667
程序3:传递字符串的顺序非常重要。更改变量将得到不同的结果。
$output1 = similar_text("with mysql", "php is best");
// To display the number of matching characters
echo "Number of similar characters : $output1\n";
$output2 = similar_text( "php is best", "with mysql");
// To display the number of matching characters
echo "Number of similar characters : $output2\n";
?>
输出:
Number of similar characters : 2
Number of similar characters : 3